How to rename and remap fields with illegal json field names - c#

I have used json2csharp to produce some nice c# class into which I can deserialize json.
It is actually working as expected EXCEPT that json2csharp named some of the fields invalid_name . I renamed those to valid csharp names but when serialized those class are null.
I found this other SO post... where one of the answerers said the following...
Keep in mind the class I have pasted below will not work directly,
because of the naming of some of the fields in the json. You may have
to rename them manually and map them.
This exactly describes my problem. Unfortunately, the answer gives no clues on actually HOW to "map them." So can someone tell me how to manually map some json arrays to c# classes.
I am using RestSharp deserializers, btw.
Any ideas?

If you are using JSON.NET as the basis or JSON parsing, you can rename your properties and then decorate them with attributes to align them back to the original JSON object.
An example is a property in JSON called 1 which is invalid in C#. This can be corrected using the following:
[JsonProperty("1")]
public int? One { get; set; }
There is also a JsonObject attribute if you want to edit at the class level, and also a JsonIgnore object to ignore serialisation of properties.

Related

Serialize class properties with their types automatically

My boss have a strange request, he wants me to add a new function to serialize and deserialize all our products classes and add in the XML file all their property's types automatically.
I can't modify the classes to add new "types properties" before every "real property".
Is there a way to do this with [XmlAttributes] or something else ?
Thank you.
Maybe this is what you are looking for https://learn.microsoft.com/dotnet/api/system.xml.serialization.xmltypeattribute?view=netcore-3.1
this article describes the XmlTypeAttribute, which you can use to add a type attribute (in xml) on your properties tag.
[XmlType("aType")]
public string MyProperty {get;set;}

Ignore a property from being serialized when trying to serialize an object to Json using JIL (like [JsonIgnore] in newtonsoft)

I've recently changed my Json serialization/deserialization logic from Newtonsoft to JIL,it(Jil) works with better performance than newtonsoft (as expected) but I have one major problem with it
My model objects are usually big objects with lots of properties including their own props and their parent props, so I can't pass the whole object to the client on every request, I usually exclude some of their properties (unnecessary ones).
In newtonsoft I easily used JsonIgnore attribute and my need was satisfied but as I googled a bit I haven't found it's (JsonIgnore) equivalent attribute in JIL.
Does this attribute exists in JIL or I should write it myself??
if the answer is no how can I write an attribute that Ignores property from being serialized with JIL because I have no access to JIL JSON.Serialize mechanism
any help would be hugely appreciated
I found the answer myself I should use JilDirective attribute with first property of false see below
[JilDirective(true)]

How to deserialize JSON into a List<KeyValuePair<string,string>> set

I have some JSON data :-
{
"mail":"mitch#domain.com",
"givenName":"User",
"sn":"Name",
"uid":"mitch",
"gecos":"User Name"
}
What I'm trying to do is de-serialize this into a List<KeyValuePair<string,string>>
I would normally do a dictionary, however some key's may be duplicated - this is the representation that is automatically generated by .NET when I pass a List<KeyValuePair<string,string>> object into the System.Web.Script.Serialization.JavaScriptSerializer class.
When I just plug the serialized object into the System.Web.Script.Serialization.JavaScriptDeserializer I get a empty response back.
From what I can see it should not be possible using the JavaScriptSerializer. The only way for customizing its behavior is by means of a JavaScriptConverter class, that will allow you to customize the serialization/deserialization process. Unfortunately both methods will pass an IDictionary for the properties, therefore the duplicated names are already merged. You might want to look into either a different format for your JSON or a different serialization library such as JSON.net which is way more customizable.

Json with a strange name field cannot be parsed

I have this JSON container that has a strange field called "48x48" for a photoUrl.
using Newtonsoft.Json;
(...)
dynamic issuesJson = JsonConvert.DeserializeObject(responseIssues.Content);
foreach (dynamic issue in issuesJson.issues){
Console.WriteLine(issue.name); //works properly
Console.WriteLine(issue.48x48); //error -> expected;
}
For some reason Visual Studio doesn't accept the access to this runtime field of this dynamic object. How can I work around this problem?
Note: I cannot change the field name.
Thanks anyway.
For some reason Visual Studio doesn't accept the access to this runtime field of this dynamic object.
Well what you've provided is simply not valid C#. An identifier can't start with a digit. That's still enforced even when you're trying to resolve a member of dynamic.
We don't know what type you're using for issues, but basically you'll need to handle it as a key/value map which you can access by string. Quite how you do that will depend on the implementation of issue. It doesn't look like Json.NET guarantees anything there - you may be able to cast it to JObject, for example:
foreach (JObject issue in issuesJson.issues) {
Console.WriteLine(issue["48x48"]);
}
Field names cannot start with a number. Sorry, no way around it.
You'll have to consult the documentation of your deserializer to see how it takes care of cases like that. It may be as simple as renaming the field "_48x48".
EDIT: actually, based on your code, you probably don't have a class representing this JSON object; I'm leaving my answer anyway, in case it helps someone else.
As others have mentioned, a C# identifier can't start with a digit. You just need to rename 48x48 to a valid name in your class, and map it to the actual JSON name using the [JsonProperty] attribute:
[JsonProperty("48x48")]
public string _48x48 { get; set; }

JavaScriptSerializer throwing ArgumentNullException on deserialization

I'm writing an application that posts and gets JSON to/from a backend in Visual C# 4.0.
Obviously, the easiest way to serialize/deserialize the JSON is System.Web.Script.Serialization.JavaScriptSerializer, but I'm having a weird error where it's throwing a ArgumentNullException, claiming that type is null.
When the following JSON is deserialized, it works fine:
{"results":[
{"Name":"Western Bulldogs",
"updatedAt":"2011-08-22T09:09:09.673Z",
"Nickname":"Bulldogs",
"RemoteId":44,
"Abbreviation":"WB",
"createdAt":"2011-08-22T09:09:09.673Z",
"objectId":"2iSK8FDTA6"}
]}
However, when deserializing the second one (with the nested dictionary), it fails with the type is null error.
{"results":[
{"EndDate":{"iso":"2011-09-06T00:00:00.000Z","__type":"Date"},
"Name":"Round 24",
"updatedAt":"2011-08-22T08:33:54.119Z",
"RemoteId":800,"createdAt":"2011-08-22T08:33:54.119Z",
"Season":{"className":"Season","__type":"Pointer","objectId":"WnsdqIlrd6"},
"Order":24,
"StartDate":{"iso":"2011-08-30T00:00:00.000Z","__type":"Date"},
"objectId":"bLdBfhagi9"}
]}
For reference, I'm deserializing with the following method for both queries:
JavaScriptSerializer jsSerialise = new JavaScriptSerializer();
ObjectIdContainerList contList = jsSerialise.Deserialize<ObjectIdContainerList>(responseString);
Where ObjectIdContainerList is as follows (note - it does not implement all the properties of the original JSON object because I am only interested in getting the objectId property):
[Serializable]
public class ObjectIdContainerList
{
public ObjectIdContainer[] results { get; set; }
}
[Serializable]
public class ObjectIdContainer
{
public String objectId { get; set; }
}
The first query deserialises without issue with exactly the same code and objects.
Any suggestions? Would I be best off just going to JSON.NET?
I don't understand what's the purpose of ObjectIdContainerList when you should be able to simply do this:
jsSerialise.Deserialize<List<ObjectIdContainer>>(responseString)
and get a List of ObjectIdContainer
I would also make sure that ObjectIdContainer has a property called "__type" that holds a string. I mention it because that's a weird name for a class property in C#.
EDIT: I just saw that you posted the rest of your code...
Are you saying that you expect to be able to deserialize the response string into an array of ObjectIdContainer where ObjectIdContainer only has a property called objectId? I would be very impressed if you can manage to make that work.
I remember Reflector once showed me that the implementation of the JavascriptSerializer basically uses reflection to serialize/deserialize objects; therefore, you need a corresponding class with the same property names as the ones defined in your JSON object or else it will fail.
I feel kind of bad for answering my own question, but I ended up solving the problem by using Json.Net to deserialise the object with almost exactly the same code and it worked.
I'm not inclined to say that this is a bug in the .Net framework, but it kind of feels that way.
Thanks to those who helped!

Categories