2

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":"user1@email.com"},{"name":"user2", "email":"user2@email.com"}]}

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

{"users":{"name":"user1", "email":"user1@email.com"}}

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

svick
  • 236,525
  • 50
  • 385
  • 514
Cheburek
  • 2,103
  • 21
  • 32

2 Answers2

2

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.

Community
  • 1
  • 1
svick
  • 236,525
  • 50
  • 385
  • 514
0

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

Sergey Savenko
  • 666
  • 6
  • 11
  • JSON.NET = Newtonsoft.JSON as I understand... It throws exception on call `JsonConvert.DeserializeObject(json)` for the second case. Can you post your solution please? – Cheburek Feb 16 '12 at 12:54
  • `public class ObjectWithAList { [JsonProperty("List")] public List List = new List(); }`. This class is easily serialized by `Newtonsoft.Json.JsonSerializer` what's the problem? – Sergey Savenko Feb 16 '12 at 21:58