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
you have to flatten all json properties, after this to convert to DataTable
output
You need to do this in two steps.
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.
Now we need to define the shape of
DataElement
.And now we need to define the shape of SportElement.
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 ofid1
,id2
,id3
, …id100
etc elements, then you can throw away theSportElement
class and use a dictionary to represent that element instead.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:
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).
Or (if for example the
sport
element could contain any number ofid1
,id2
and so on elements) you might want it to look like this.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.