Cheburek
Cheburek

Reputation: 2113

Deserializing JSON object into .NET List

JSON is created in Java using Jersey's JAXB serializer. I need to deserialize it in .NET application. The problem is in serialized arrays: if array contains several items JSON object is like that:

{"users":[{"name":"user1", "email":"[email protected]"},{"name":"user2", "email":"[email protected]"}]}

but when object contains only one item it is serialized as a simple object

{"users":{"name":"user1", "email":"[email protected]"}}

I want to deserialize it into .NET object.

public class UserList{
   public List<User> users {get;set;}
}
public class User{
   public string name {get;set;}
   public string email {get;set;}
}

Standard .NET deserializer does not understand the second case. I tried JSON.NET default deserializer but it throws exception. Maybe it needs to be configured properly?.. Can you suggest something how to deal with first and second cases. P.S. I have no access to the Java serializer

Upvotes: 2

Views: 4452

Answers (2)

svick
svick

Reputation: 244757

In Json.Net, you can create a custom converter that can handle JSON like this.

Have a look at Deserializing JSON when sometimes array and sometimes object on how exactly to do that.

Upvotes: 2

Sergey Savenko
Sergey Savenko

Reputation: 666

I've been using Newtonsoft.JSON for this purpose and it did manage with serializing collections very good. Try it.

Upvotes: 0

Related Questions