Deserializing JSON into an object with Json.NET

后端 未结 3 911
孤街浪徒
孤街浪徒 2020-12-03 05:05

I\'m playing a little bit with the new StackOverflow API. Unfortunately, my JSON is a bit weak, so I need some help.

I\'m trying to deserialize this JSON of a User:<

相关标签:
3条回答
  • 2020-12-03 05:36

    As Alexandre Jasmin said in the comments of your question, the resulting JSON has a wrapper around the actual User object you're trying to deserialize.

    A work-around would be having said wrapper class:

    public class UserResults
    {
        public User user { get; set; }
    }
    

    Then the deserialization will work:

    using (var sr = new StringReader(json))
    using (var jr = new JsonTextReader(sr))
    {
        var js = new JsonSerializer();
        var u = js.Deserialize<UserResults>(jr);
        Console.WriteLine(u.user.display_name);
    }
    

    There will be future metadata properties on this wrapper, e.g. response timestamp, so it's not a bad idea to use it!

    0 讨论(0)
  • 2020-12-03 05:36

    Similar to @Alexandre Jasmin's answer, you can use an intermediary JsonSerializer to convert instead of the using the high-level JsonConvert on .ToString(). No idea if it's any more efficient...

    References:

    • https://stackoverflow.com/a/9453198/1037948
    • http://www.west-wind.com/weblog/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing

    Example:

    var root = JObject.Parse(jsonString);
    var serializer = new JsonSerializer();
    var expectedUserObject = serializer.Deserialize<User>(root["user"].CreateReader());
    
    0 讨论(0)
  • 2020-12-03 05:42

    If you don't want to create a wrapper class you can also access the User this way:

    String jsonString = "{\"user\":{\"user_id\": 1, \"user_type\": \"moderat...";
    JToken root = JObject.Parse(jsonString);
    JToken user = root["user"];
    User deserializedUser = JsonConvert.DeserializeObject<User>(user.ToString());
    

    See this page in the Json.NET doc for details.

    0 讨论(0)
提交回复
热议问题