Steven Yong Steven Yong - 3 months ago 43
C# Question

Serialise JSON to C# object into ArrayList of objects

I have the following JSON:

{
"id": "3cf5373c-9181-4639-89f0-bb64b387f961",
"display": "Data 1",
"country": "AU"
}


and I know how to construct the class to serialize it:

[DataContract]
public class myJSONClass
{

[DataMember(Name = "id")]
public string Id { get; set; }

[DataMember(Name = "display")]
public string Display { get; set; }

[DataMember(Name = "country")]
public string Country { get; set; }
}


and I use the below to serialize:

var url = "http://myJSONAPI/";

var syncClient = new WebClient();
var content = syncClient.DownloadString(url);

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(myJSONClass));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
var jsonData = (myJSONClass)serializer.ReadObject(ms);
}


But how would I go about defining my class if my JSON is like the below?

[
{
"id": "3cf5373c-9181-4639-89f0-bb64b387f961",
"display": "My Data 1",
"country": "AU"
},
{
"id": "8886d2c8-0fd5-49ff-a3e1-7cef9e654514",
"display": "no test",
"country": null
}
]


How would like declare my class?

And how do I serialize it? I cannot use JSON.net as I cannot use newer .Net framework.

Answer

[] - It's array. So after deserialization you should get single array object of your class(myJSONClass)

myJSONClass[] deserializedData=deserialize(jsonData);

So if you want to get a deserialized array of objects you should just serialize not a single object but an array(several objects of your class)

But you doing something strange in example because you downloaded string and trying to serialize it. But you received serialized data(string is serialized. Object can be created by deserializing json(or xml) string).

So if you actually received 2 objects in array(as in your last JSON sample) your code should be more like this:

    var url = "http://myJSONAPI/";
    var syncClient = new WebClient();
    var content = syncClient.DownloadString(url);

    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(myJSONClass[]));
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
    {
        myJSONClass[] jsonObject = (myJSONClass[])serializer.ReadObject(ms);
    }

I renamed some variables for better understanding. Also now you deserialize array of your class.

Also i found this thread: Deserialization of array with DataContractJsonSerializer with Windows Store App

But my own advice is to look at NewtonsoftJSON. It's really sweet http://www.newtonsoft.com/json/help/html/deserializeobject.htm So then you could achieve everything jus by one line:

myJSONClass[] res = JsonConvert.DeserializeObject<myJSONClass[]>(json_string);
Comments