Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a Json string that has an array of objects but is not using square brackets

Tags:

json

c#

json.net

I'm trying to deserialize a Json string that has an array with no containing brackets.

{ "id": "983f90j30909j3f",
  "moreInfo": {
      "info193802": { ... },
      "info920938": { ... },
      "info849028": { ... }
  }
}

This "moreInfo" is an array of items with dynamic keys and does not have square brackets telling that it's an array.

I've tried to deserialize it with Newtonsoft.Json normally ( JsonConvert.DeserializeObject<rootObject>() ) but since this json array isn't really an array it throws an error. Here is my class:

public class RootObject
{
    public string Id { get; set; }
    public MoreInfo MoreInfo { get; set; }
}


public class MoreInfo
{   
    public List<Info> InfoList{ get; set; }
}

public class Info
{
    properties...
}

How do I go about deserializing this?

like image 662
aweyeahdawg Avatar asked Nov 17 '25 12:11

aweyeahdawg


2 Answers

Update the root object to use IDictionary<string, Info>

public class RootObject {
    public string Id { get; set; }
    public IDictionary<string, Info> MoreInfo { get; set; }
}

the dynamic keys will be the key in the dictionary.

Once parsed you access the info via the dictionary's keys

Info info = rootObject.MoreInfo["info193802"];
like image 120
Nkosi Avatar answered Nov 20 '25 02:11

Nkosi


Newtonsoft can correctly parse the data. The data represents objects, they happen to be nested fairly deep. You can accomplish it a couple of ways, for instance:

dynamic json = JsonConvert.DeserializeObject(response);
var info = json["moreinfo:info913802:example"].Value;

Your other option would be to use Visual Studio, let it create an object you can deserialize to.

  1. Edit
  2. Paste Special
  3. As JSON

Output would be:

public class Rootobject
{
    public string id { get; set; }
    public Moreinfo moreInfo { get; set; }
}

public class Moreinfo
{
    public Info193802 info193802 { get; set; }
    public Info920938 info920938 { get; set; }
    public Info849028 info849028 { get; set; }
}

public class Info193802
{
    public string Example { get; set; }
}

public class Info920938
{
    public string Example { get; set; }
}

public class Info849028
{
    public string Example { get; set; }
}

The source JSON I used was yours, with one exception:

{ "id": "983f90j30909j3f",
  "moreInfo": {
      "info193802": { "Example" : "Blah" },
      "info920938": { "Example" : "Blah" },
      "info849028": {"Example" : "Blah" }
  }
}
like image 42
Greg Avatar answered Nov 20 '25 01:11

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!