1

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?

Community
  • 1
  • 1

2 Answers2

2

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.

Bozhidar Stoyneff
  • 3,576
  • 1
  • 18
  • 28
2

To your first question:

I would consider the option with the Cover class the 'best practice' as you are using the same model for serialization and deserialization and it's all up to Json.NET to figure out how to do the (de)serialization magic.

If for some reason you don't want to use this approach, there are two other options:

To your second question - Are you sure the generated JSON is absolutely the same with both approaches? (You can use a tool like www.diffchecker .com to verify)

With your second approach the top-level names should be different - it should be 'Users' instead of 'UserList' and 'Requests' instead of 'RequestList'

  • Thanks for the reply. You're right, the jsons are different. Of the 3 options, work with the same type of objects to serialize / deserialize seems to be the best practice. About Deserializing into a dictionary: not working for me. Greatly help your links. –  Jun 05 '16 at 17:14