Anand Dubey Anand Dubey - 1 year ago 82
JSON Question

Deserialize json data without using Json.net

I am working in schedule agent. I have data in json format in schedule agent. I tried Json.net in schedule agent to deserialize json into list, but it is not working in schedule agent.

Can anyone tell me how I can deserialize json data into a list format without using Jsonssoft.dll??

I am using following code to convert json to list but it is giving me null in childlist...

List<ConferenceModel> childlist = new List<ConferenceModel>();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseContent));
DataContractJsonSerializer ser = new DataContractJsonSerializer(childlist.GetType());
childlist = ser.ReadObject(ms) as List<ConferenceModel>;


Here is ConferenceModel class

public class Conference
{
public string id { get; set; }
public string datetime { get; set; }
public string updateDateTime { get; set; }
public int duration { get; set; }
public string description { get; set; }
private bool _isEditDeleteVisible;

}
public class ConferenceModel
{
public List<Conference> conferences { get; set; }
}

Answer Source

Try to use the DataContract annotation in your model + use the DataContractJsonSerializer and it should work just fine:

[DataContract]
public class Conference
{
    [DataMember]
    public string id { get; set; }
    [DataMember]
    public string datetime { get; set; }
    [DataMember]
    public string updateDateTime { get; set; }
    [DataMember]
    public int duration { get; set; }
    [DataMember]
    public string description { get; set; }
    [IgnoreDataMember]
    private bool _isEditDeleteVisible;
}

[DataContract]
public class ConferenceModel
{
    [DataMember]
    public List<Conference> conferences { get; set; }
}

Edit: The code needs to be fixed as well - this worked for me:

MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ConferenceModel));
ConferenceModel childlist = (ConferenceModel)ser.ReadObject(ms);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download