1

How can I use DataContractJsonSerializer to parse a JSON array which does not have a fix name? Suppose a JSON Structure like this:

{
 "SUMMARY":
 {
    "0123":
    [
    {
       "Type": "Type_A",
       "Duration": 100
    }
    ]
 }
}

In C#, I can initialise two data objects as below to parse them using DataContractJsonSerializer like this:

[DataContract]
public class numberedStruct {

    [DataMember(Name = "Type")]
    public string Type {get; set;}

    [DataMember(Name = "Duration")]
    public int Duration{get; set;}
}

[DataContract]
public class summaryStruct {

    [DataMember(Name = "0123")]
    public numberedStruct[] s;

}

However, what if "0123" is also a variable and it can be something else? So I cannot fix the DataMember name as "0123".

How can I get "0123" as an variable and also the content within the struct in C#?

Alan Hung
  • 41
  • 1
  • Depends, the structure is the same and the place in the structure is always the same for "0123"? – Juan Pablo Garcia Coello Apr 17 '15 at 05:11
  • variable names cannot be number in c#. – ANewGuyInTown Apr 17 '15 at 05:25
  • Thanks for your comments. "0123" is just an example. Actually it's not the name of the variable, it's the value of variable in the real case so it can be "abcd", or "defg". I'm not sure how to parse this type of structure because it doesn't have a static variable name. – Alan Hung Apr 20 '15 at 02:00

1 Answers1

0

you could try putting your strange variables name in dictionary with [JsonExtensionData]

[JsonExtensionData]
public Dictionary<string, object> strangeVariables { get; set; } 

This will go within the Response object.

ANewGuyInTown
  • 5,957
  • 5
  • 33
  • 45
  • Hi ANewGuylnTown, thanks for your suggestion. Can you please give me the code in details. I tried the structure below but it still returns a null value for me. [DataContract] public class summaryStruct { [JsonExtensionData] public IDictionary s; } – Alan Hung Apr 20 '15 at 02:03
  • Thank you very much. It's not working. I have to use the serialize/deserialize function provided in Newtonsoft.Json.JsonConvert as well in order to get it. Using the .NET default DataContractJsonSerializer won't work. – Alan Hung Apr 21 '15 at 00:01