Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DataContractJsonSerializer fails when value can be an array or a single item

I use the DataContractJsonSerializer to parse a json string into a object hierarchie. The json string looks like this:

{
    "groups": [
        {
            "attributes": [
                {
                    "sortOrder": "1",
                    "value": "A"
                },
                {
                    "sortOrder": "2",
                    "value": "B"
                }
            ]
        },
        {
            "attributes": {
                "sortOrder": "1",
                "value": "C"
            }
        }
    ]
}

As you can see the sub value of "attributes" can be an array or a single item. I found the code part where the problem occures:

[DataContract]
public class ItemGroup
{
    [DataMember(Name="attributes")]
    public List<DetailItem> Items  { get; set; }
}

This works for the first one but fails on the second one.

Has anyone an answer for this?

Thx

like image 308
Marco Avatar asked Oct 04 '11 12:10

Marco


2 Answers

If you control how the JSON is created then make sure that attributes is an array even if it only contains one element. Then the second element will look like this and parse fine.

    {
        "attributes": [{
            "sortOrder": "1",
            "value": "C"
        }]
    }
like image 95
Daniel Elliott Avatar answered Oct 19 '22 02:10

Daniel Elliott


As Daniel said, if you can control the creation of Json, it is better to continue that way. But if you can't, then you can use Json.Net library & the JsonObject class from this link to write some code like:

JObject o = (JObject)JsonConvert.DeserializeObject(input);
dynamic json = new JsonObject(o);
foreach (var x in json.groups)
{
      var attrs = x.attributes;
      if (attrs is JArray)
      {
           foreach (var y in attrs)
           {
               Console.WriteLine(y.value);
           }
      }
      else
      {
          Console.WriteLine(attrs.value);
      }
 }
like image 3
L.B Avatar answered Oct 19 '22 03:10

L.B