Arun
Arun

Reputation: 1472

Deserialize json Object using newtonsoft json

I have a json like

{"NewMessage":[{"Id":-1,"Message":"Test","MessageName":"test1"}],"OldMessage":[]}

and I need to deserialize this json in to my class object.

My Class

public class NewMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}

public class OldMessage{
public int Id{get;set;}
public string Message{get;set;}
public string MessageName{get;set;}
}

how can we achive this by using newtonsoft.json. can anyone help. thanks in advance

Upvotes: 0

Views: 65

Answers (1)

Bozhidar Stoyneff
Bozhidar Stoyneff

Reputation: 3634

Your JSON actually contain an object which have properties of your defined classes - given the code posted, you don't have a class to deserialize into.

The first thing you can do is obvious - create a third class - MessagePair - which declares two properties - NewMessage[] and OldMessage[]. Then you can deserialize the JSON string like this:

var theMessages = JsonConvert.DeserializeObject<MessagePair>(jsonText);

If you don't like to create separate class, you can then deserialize into anonymous object like this:

var theMessages = new { 
    NewMessage[] NewMessages = null, 
    OldMessage[] OldMessages = null 
};

theMessages = JsonConvert.DeserializeAnonymousType(jsonText, theMessages);

Upvotes: 2

Related Questions