Deserializing a small, fixed size, fixed structure, with fixed field names, JSON string is easy: Just define a class that contains all the fields (with correct types and names, all known at compile time).
Deserializing a variable-size of repeating nested pairs, is somewhat more challenging but can be done with the help of a List<> inside the class.
But what do I do when the name of the fields are unknown at compile time? e.g.:
{
"container":{
"GD01AB491103":{
"field_id1":11,
"field_id2":12,
"field_id3":13,
"field_id4":"fourteen"
},
"DC01AB491103":{
"field_id1":21,
"field_id2":22,
"field_id3":23,
"field_id4":"twenty four"
},
"GH01AB451101":{
"field_id1":31,
"field_id2":32,
"field_id3":33,
"field_id4":"thirty four"
}
.
.
.
},
"terminator"
}
How to deserialize such a string?
(preferably with .NET's JavaScriptSerializer but if it's too weak/incapable, I might need to resort to something else)
Edit: To clarify the nature of the challenge: In the example above, in order to define a class:
public class ??????
{
public int field_id1 {get;set;}
public int field_id2 {get;set;}
public int field_id3 {get;set;}
public string field_id4 {get;set;}
}
I need to query the JSON string first, then at runtime build classes (reflection?) with these variable-name class objects in it? Looks too cumbersome... Perhaps there is a saner way?
Or maybe the class/field names are irrelevant to .NET's JavaScriptSerializer and all matters is the type? (and correct structure of course)
You can do this probably more simply than you think.. your ?????? class can be anything..
public class GenericObject
{
public int field_id1 {get;set;}
public int field_id2 {get;set;}
public int field_id3 {get;set;}
public string field_id4 {get;set;}
}
and then deserialize the root of the object graph into an object that contains a Dictionary<string,GenericObject>...
public class SomeContainer
{
public Dictionary<string,GenericObject> container {get;set;}
}
you can then loop over the values of the dictionary if you don't care about the names of the keys.
Related
Is it possible to deserialize a JSON into a class where a property name could be one of two values?
For example both of these JSONs would deserialize into the same property:
var json1 = "{\"A\":5}";
var json2 = "{\"B\":5}";
I thought that maybe I could use the JsonPropertyName attribute twice.
[JsonPropertyName("A")]
[JsonPropertyName("B")]
public int SomeInt { get; set; }
This is not allowed.
Then I thought maybe if the deserializer could not find the JsonPropertyName attribute it would look for the actual property name.
[JsonPropertyName("A")]
public int B { get; set; }
But that doesn't work either.
You could have two separate properties, with one delegating to another:
[JsonPropertyName("A")]
[Obsolete("Explain why here")]
public int A
{
get => B;
set => B = value;
}
[JsonPropertyName("B")]
public int B { get; set; }
The downside is that both will be written when serializing. I'd originally thought you could use JsonIgnoreAttribute for the obsolete property, but that would prevent it from being deserialized too :( Not so bad if you're only using this for parsing, but unpleasant if you're serializing too.
Additionally, if you ever parse a JSON file with both of them, whichever one is set last will win, which may not be ideal.
There are a number of great ways to auto-generate C# code from JSON, such as here and here.
However, the resulting code doesn't include property initializers. For example, the following JSON:
{
"Name" : "Blastoise"
}
gets deserialized to this:
public class RootObject
{
public string Name { get; set; }
}
Presumably this is by design, since the values used in the JSON will probably be overridden anyways, so adding initializers might just annoy people who don't want them.
But what if I want that? Short of manually adding every value by hand, is there a way to deserialize JSON to the following?
public class RootObject
{
public string Name { get; set; } = "Blastoise";
}
Obviously in this case a manual edit is easy, but manual editing becomes tedious for larger JSON objects.
is there a way to deserialize JSON to the following?
Using the source code of the converter you mentioned.
A quick change at the line 204
sw.WriteLine(prefix + "public {0} {1} {{ get; set; }} = {2};", field.Type.GetTypeName(), field.MemberName, field.GetExamplesText());
gives me the result similar to what you described
internal class SampleResponse1
{
[JsonProperty("Name")]
public string Name { get; set; } = "Blastoise";
}
i have an XML form look like this:
<Myset>
<element>1A</element>
<element>2B</element>
<element>3C</element>
<element>AB</element>
..........
<element>AA</element>
What should structure class, variables should i use to deserialize it. I want to read and update value of each element. I have try this, but it doesn't work:
public class Myset
{
public List<string> element {get; set;}
// or public string[] element { get; set; }
}
XmlElementAttribute will allow you specify element name.
public class case_id_list
{
[XmlElement("case_id")]
public List<string> case_id {get; set;}
}
You should use this service. It converts your xml structure to valid c# model structure. It's a very useful tool.
*In case you ever want to convert your JSON to C# this is another useful service.
Cheers!
I am retrieving and successfully deserializing an xml string from a database table column for the known element names (these do not change) but there are also some nested XML Elements called "Other Attributes" which are not always going to be known. I'm having some trouble deserialising these unknown element names to a generic list so I can display them in html once deserialised.
The XML is as follows:
<Detail>
<DetailAttributes>
<Name>Name_123</Name>
<Type>Type_123</Type>
</DetailAttributes>
<OtherAttributes>
<SummaryKey AttributeName="SummaryKey">SummaryKey_123</SummaryKey>
<Account AttributeName="Account">Account_123</Account>
</OtherAttributes>
</Detail>
I have no problem deserialising the 'Name' and 'Type' elements and I can deserialise the 'SummaryKey' and 'Account' elements but only if I explicitly specify their element names - which is not the desired approach because the 'OtherAttributes' are subject to change.
My classes are as follows:
[XmlRoot("Detail")]
public class objectDetailsList
{
[XmlElement("DetailAttributes"), Type = typeof(DetailAttribute))]
public DetailAttribute[] detailAttributes { get; set; }
[XmlElement("OtherAttributes")]
public List<OtherAttribute> otherAttributes { get; set; }
public objectDetailsList()
{
}
}
[Serializable]
public class Detail Attribute
{
[XmlElement("Type")]
public string Type { get;set; }
[XmlElement("Name")]
public string Name { get;set; }
public DetailAttribute()
{
}
}
[Serializable]
public class OtherAttribute
{
//The following will deserialise ok
//[XmlElement("SummaryKey")]
//public string sumKey { get; set; }
//[XmlElement("Account")]
//public string acc { get; set; }
//What I want to do below is create a list of all 'other attributes' without known names
[XmlArray("OtherAttributes")]
public List<Element> element { get; set; }
}
[XmlRoot("OtherAttributes")]
public class Element
{
[XmlAttribute("AttributeName")]
public string aName { get; set; }
[XmlText]
public string aValue { get; set; }
}
When I try to retrieve the deserialised list of OtherAttribute elements the count is zero so it's not able to access the elements nested within "Other Attributes".
Can anybody help me with this please?
With concrete classes and dynamic data like this, you won't be able to lean on the standard XmlSerializer to serialize / deserialize for you - as it reflects on your classes, and the properties you want to populate simply don't exist. You could provide a class with all possible properties if your set of 'OtherAttributes' is known and finite, and not subject to future change, but that would give you an ugly bloated class (and I think you've already decided this is not the solution).
Practical options therefore:
Do it manually. Use the XmlDocument class, load your data with .Load(), and iterate the nodes using .SelectNodes() using an XPath query (something like "/Detail/OtherAttributes/*"). You will have to write the lot yourself, but this gives you complete control over the serialization / deserialization. You won't have to cover your code in (arguably superfluous!) attributes either.
Use Json.NET (http://james.newtonking.com/json), it allows for far greater control over serialization and deserialization. It's fast, has good docs and is overall pretty nifty really.
i'm working with Microsoft Json library. (DataContractJsonSerializer)
i thought it was a nice library but it caught very hard problem for me.
first, please see the screenshot please.
the json file was clear. because i test it some online json parse sites like here
a problem is it'cant deserialize json rightly. it was cracked.
i. terms[0].labels=null. but as web parser showed, it contains 'labels' structure.
ii. terms1.labels!=null. but as web parser showed, it contains nothing. (terms1 doesn't 'labels' structure, instead terms[0]
a problem is not only that.
the 'primaries' contains number of two array originally, but microsoft json returns just one member only.
even, terms1.labels[0].text have a string value "[US]" but, a string "[US]" is not exist in entire json string!
here is my structure for json.
[DataContract]
public struct GDicJson
{
[DataMember] public string query;
[DataMember] public string sourceLanguage;
[DataMember] public string targetLanguage;
[DataMember] public List<GDicResultContent> primaries;
[DataMember] public List<GDicResultContent> webDefinitions;
[DataContract]
public struct GDicResultContent
{
[DataMember] public string type;
[DataMember] public List<GDicResultTerm> terms;
[DataMember] public List<GDicResultEntry> entries;
}
[DataContract]
public struct GDicResultTerm
{
[DataMember] public string type;
[DataMember] public string text;
[DataMember] public string language;
[DataMember] public List<GDicResultLabel> labels;
}
[DataContract]
public struct GDicResultLabel
{
[DataMember] public string text;
[DataMember] public string title;
}
[DataContract]
public struct GDicResultEntry
{
[DataMember] public string type;
[DataMember] public List<GDicResultTerm> terms;
[DataMember] public List<GDicResultEntry> entries;
}
}
i like to my source json file but StackOverflow doesn't provide upload file. i'm sorry for that.
anyway, help me anybody.
if you want, i'll send a json file to your email with my source code.
But still as suggested by #StriplingWarrior, Json.NET has some issues too. I had a correct Json string containing basically just arrays within squared brackets and Json.NET was unable to parse it correctly and was returning nulls. I used fastJSON instead and all problems were solved. Plus is a way faster library than Json.NET. Give it a look at http://www.codeproject.com/KB/IP/fastJSON.aspx it also pretty easy to implement.
This is just a guess but it could be that because you're using structs, it's not updating instance's field upon deserialization. Can you change these to be classes instead of structs and try it out?