Fernanda Ines Duran Fernanda Ines Duran - 6 months ago 533
JSON Question

JSON Newtonsoft C# Good Practice for Serialize/ Deserialize Lists of Objects

I've readed others posts here about this question

Serializing a list of Object using Json.NET

Serializing a list to JSON

Merge two objects during serialization using json.net?

All very useful. Certain, I can serialize in one json two lists, but I cant deserialize it.

I´m working with Json Newtonsoft, C#, MVC5, framework 4.5. This is the scenario:

C# CODE

public class User
{
public int id { get; set; }
public string name { get; set; }
}

public class Request
{
public int id { get; set; }
public int idUSer{ get; set; }
}

List<User> UserList = new List<User>();
List<Request> RequestList = new List<Request>();
string json= JsonConvert.SerializeObject(new { UserList, RequestList });


JSON RESULT

{
"UserList":[
{
"id":1,
"name":"User 1"
},
{
"id":2,
"name":"User 2"
},
{
"id":3,
"name":"User 3"
}
],
"RequestList":[
{
"id":1,
"idUSer":1
},
{
"id":2,
"idUSer":1
},
{
"id":3,
"idUSer":1
},
{
"id":4,
"idUSer":2
}
]
}


C# DESERIALIZE

I dont Know how configure the settings of Json.Deserialize< ?, Settings>(json) for indicate what types of objects are being deserialized.

Change of approach

So that, change of approach, I've created a new class "Cover" in order to put the lists together and serialize one object

public class Cover
{
private List<User> user = new List<User>();
private List<Request> request = new List<Request>();

public List<User> User
{
get { return user;}
set { User = value;}
}

public List<Request> Request
{
get {return request;}
set {Request = value;}
}
}


SERIALIZE

string json = JsonConvert.SerializeObject(cover);


JSON The json result is the same.

DESERIALIZE

Cover result = JsonConvert.DeserializeObject<Cover>(json, new
JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });


It's work fine. My situation is resolved but I have doubts about concepts, in my mind something is not clear:

MY QUESTIONS ARE:

For the first aproach:

Do you think that there is a way to deserialize a json with different lists of objects? Is not a good practice?

Second aproach: Why jsons are equals for first situation?

Answer

In JSON.NET you need to specify the type you're about to deserialize, by supplying its name as a type argument to DeserializeObject. However, in this line:

string json=  JsonConvert.SerializeObject(new { UserList, RequestList });

you create anonymous object and then serialize it - new { UserList, RequestList }. So there is the catch - you cannot use anonymous type as type arguments. To handle such situations, JSON.NET provides DeserializeAnonymousType<>. It doesn't require you to supply the type argument; actually you can't as you going to deserialize anonymous type. Instead it is inferred from the type of the second argument, passed to the method. So you just create a dummy, anonymous object, without data and pass it to this method.

// jsonData contains previously serialized List<User> and List<Request>
void DeserializeUserAndRequest(string jsonData) 
{
    var deserializedLists = new { 
        UserList = new List<User>(), 
        RequestList = new List<Request>() 
    };
    deserializedLists = JsonConvert.DeserializeAnonymousType(jsonData, deserializedLists);

    // Do your stuff here by accessing 
    //  deserializedLists.UserList and deserializedLists.RequestLists
}

Of course this all works fine, but this approach suggests that you already know the structure of the serialized data. If this structure doesn't match the structure of the initialized by you anonymous type you'll get nothing after the DeserializeAnonymousType method. And this is valid not just for the type of the properties of the anonymous type, but for their names too.