skip to Main Content

I have this very simple JSON string:

{
    "data": {
        "id": 33306,
        "sport": {
            "id1": "FB",
            "id2": "HB"
        }
     }
}

I can’t understand how to return a datatable from this string.

I have tried to use this code but it’s not working:

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

2

Answers


  1. you have to flatten all json properties, after this to convert to DataTable

        var jObj = (JObject)JObject.Parse(json)["data"];
        var properties = jObj.Properties().ToList();
        
        for (var i = 0; i < properties.Count; i++)
        {
            var prop = properties[i];
            if (prop.Value.Type == JTokenType.Object)
            {
                foreach (var p in ((JObject)prop.Value).Properties())
                    jObj.Add(new JProperty(prop.Name + " " + p.Name, p.Value));
                prop.Remove();
            }
        }
    
        DataTable dt = new JArray { jObj }.ToObject<DataTable>();
    

    output

    [
      {
        "id": 33306,
        "sport id1": "FB",
        "sport id2": "HB"
      }
    ]
    
    Login or Signup to reply.
  2. You need to do this in two steps.

    1. Deserialize into a .net object whose structure matches that of the JSON
    2. Populate a DataTable with the properties of that object

    Step 1 – Deserialize

    We need to define some classes to receive the deserialized data. The names of the classes aren’t particularly important (as long as they’re meaningful to you), however the names of the properties of those classes need to match the names of the corresponding elements in the JSON.

    First the outermost class, which is the shape of the JSON you want to deserialize.

    public class SomeClass
    {
        public DataElement Data { get; set; }
    }
    

    Now we need to define the shape of DataElement.

    public class DataElement
    {
        public int Id { get; set; }
        public SportElement Sport { get; set; }
    }
    

    And now we need to define the shape of SportElement.

    public class SportElement
    {
        public string Id1 { get; set; }
        public string Id2 { get; set; }
    }
    

    The implementation above is fairly rigid and assumes that the shape of the JSON doesn’t change from one document to the next. If, however, you expect the shape to vary, for example, if the sport element could could contain any number of id1, id2, id3, … id100 etc elements, then you can throw away the SportElement class and use a dictionary to represent that element instead.

    public class DataElement
    {
        public int Id { get; set; }
        public Dictionary<string, string> Sport { get; set; }
    }
    

    Which of those two approaches to use will depend on how predictable the structure of the JSON is (or whether or not it’s under your control). I find that using a dictionary is a good way of coping with JSON produced by 3rd party applications which aren’t under my control, but the resulting objects aren’t as easy to work with as those where I know exactly what shape the JSON will always be and can create a strongly-typed class structure representing that shape.

    Whichever approach you choose, the usage is the same:

    var deserialized = JsonConvert.DeserializeObject<SomeClass>(json);
    

    Step 2 – Populate the DataTable from the object

    How to do this step will depend on what you want the DataTable to look like (which is not clear from the question). For example, you might want it to look like this (which I think is what Serge’s answer would return).

    id sport id1 sport id2
    33306 FB HB

    Or (if for example the sport element could contain any number of id1, id2 and so on elements) you might want it to look like this.

    id sport
    33306 id1: FB
    33306 id2: HB

    Or you might want some different representation altogether. Sorry if that’s an incomplete answer, if you want to update the question with what you’d expect the DataTable to look like then I can update this answer with more detail on how to go about step 2.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search