I'm getting my data from a website which returns a .json format that is quite unfamiliar to me. I've been looking for the solution for a couple of hours, and I must be using the terminology.
The json is formatted something like this:
[
{
"Foo": {
"name": "Foo",
"size": {
"human": "832.73kB",
"bytes": 852718
},
"date": {
"human": "September 18, 2017",
"epoch": 1505776741
},
}
},
{
"bar": {
"name": "bar",
"size": {
"human": "4.02MB",
"bytes": 4212456
},
"date": {
"human": "September 18, 2017",
"epoch": 1505776741
}
}
}]
I'm using Newtonsoft's JSON.NET, and I can't seem to be able to create a data structure that would allow me to deserialize it, since it's the array of classes with different names. Specifically the property names "Foo"
and "bar"
could differ at runtime. Property names elsewhere in the JSON hierarchy are known.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Assuming that only the names "Foo"
and "Bar"
are unknown at compile time, you can deserialize that JSON into a List<Dictionary<string, RootObject>>
, where RootObject
is a c# model I generated automatically using http://json2csharp.com/ from the JSON for the value of "Foo"
.
Models:
public class Size
{
public string human { get; set; }
public int bytes { get; set; }
}
public class Date
{
public string human { get; set; }
public int epoch { get; set; }
}
public class RootObject
{
public string name { get; set; }
public Size size { get; set; }
public Date date { get; set; }
}
Deserialization code:
var list = JsonConvert.DeserializeObject<List<Dictionary<string, RootObject>>>(jsonString);
Notes:
The outermost type must be an enumerable such List<T>
since the outermost JSON container is an array -- a comma-separated sequence of values surrounded by [
and ]
. See Serialization Guide: IEnumerable, Lists, and Arrays.
When a JSON object can have arbitrary property names but a fixed schema for property values, it can be deserialized to a Dictionary<string, T>
for an appropriate T
. See Deserialize a Dictionary.
Possibly bytes
and epoch
should be of type long
.
Working .Net fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With