views:

188

answers:

1

Hi there,

I got stuck with Json.NET library and its DeserializeObject method. The Documentation is not quite clear with what could be happening here, so I would appreciate if somebody could explain how to acheive to deserialize JSON into list of User objects.

I'm trying to deserialize this JSON

[
    {"userid":"0",
     "listid":1,
     "lastname":"Mann",
     "inplace":true,
     "xpos":428,
     "ypos":111
    },
    {"userid":"1",
     "listid":1,
     "lastname":"Parker",
     "inplace":true,
     "xpos":334,
     "ypos":154
    },
    {"userid":"2",
     "listid":1,
     "lastname":"Terry",
     "inplace":true,
     "xpos":513,
     "ypos":160
    }
]

into an User object

[JsonObject(MemberSerialization.OptIn)]
public class User
{
    [JsonProperty(PropertyName = "userid")]
    public string userid { get; set; }
    [JsonProperty(PropertyName = "listid")]
    public int listid { get; set; }
    [JsonProperty(PropertyName = "lastname")]
    public string lastname { get; set; }
    [JsonProperty(PropertyName = "inplace")]
    public bool inplace { get; set; }
    [JsonProperty(PropertyName = "xpos")]
    public int xpos { get; set; }
    [JsonProperty(PropertyName = "ypos")]
    public int ypos { get; set; }

    public User()
    {
    }
}

using

List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonUsers);

without success. Not getting any error, nor users. JsonConvert.DeserializeObject just dies silently.

I tried to create mockup and to do SerializeObject and DeserializeObject with that JSON string but with same result, no errors, no results.

I even try to pass serializersettings in order to se what is wrong but with no errors either

JsonSerializerSettings settings = new JsonSerializerSettings();

settings.Error += delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) {
                    errorList.Add(args.ErrorContext.Error.Message);
              };
List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonUsers, settings);

When I try to see what is happening during deserialization I notice that context is not initialized?!

public class User
{
    ...
    [OnDeserializing]
    internal void OnDeserializing(StreamingContext context) {
    }
}

What I'm doing wrong here? And how I can deserialize this into an list of Users?

+1  A: 

I found what was problem. JSon.NET was deserializing my integers from JSON to Int64 instead to Int32 so instead of int I put long and everything worked as it should in the first place.

Is there a way to specify that I want that properties to deserialize into int?