Why does this anonymous type not deserialize properly using JsonConvert.DeserializeAnonymousType?

帅比萌擦擦* 提交于 2019-12-10 14:50:36

问题


I have the JSON string:

{"response":{"token":"{\"token\":\"123\",\"id\":191}"}}

And then I have the following code to Deserialize it, but it is returning null:

 var def = new
       {
           token = new { token = string.Empty, id= string.Empty }
        };

  var deserializedToken = JsonConvert.DeserializeAnonymousType(token, def);

deserializedToken is null

Here is a more detailed example that I can't get to work:

var def = new
            {
                code = string.Empty,
                message = string.Empty,
                url= string.Empty,
                token = new {token = string.Empty}
            };

            var response = JsonConvert.DeserializeAnonymousType(data, def);

            var innerDef = new { token= string.Empty, id= string.Empty };

            var deserializedInner = JsonConvert.DeserializeAnonymousType(response.token.token, innerDef);

回答1:


There are two problems here, as far as I can tell:

  • You don't have a response property to deserialize
  • The "token:123 id:191" part is actually just a string - the value of the outer token property

So if you change your code to:

var def = new
{
    response = new { token = "" }
};

var deserializedToken = JsonConvert.DeserializeAnonymousType(json, def);
Console.WriteLine(deserializedToken);

then you'll end up with:

{ response = { token = {"token":"123","id":191} } }

If you want to deserialize the token/id part as well, you can do that with:

var innerDef = new { token = "", id = "" };
var deserializedInner = JsonConvert.DeserializeAnonymousType
    (deserializedToken.response.token, innerDef);
Console.WriteLine(deserializedInner);

That then prints:

{ token = 123, id = 191 }


来源:https://stackoverflow.com/questions/20123398/why-does-this-anonymous-type-not-deserialize-properly-using-jsonconvert-deserial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!