为什么这个匿名类型没有使用JsonConvert.DeserializeAnonymousType正确反序列化?

时间:2013-11-21 14:20:30

标签: c# .net json json.net json-deserialization

我有JSON字符串:

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

然后我有以下代码来反序列化它,但它返回null:

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

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

deserializedToken为空

这是一个我无法开展工作的更详细的例子:

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);

2 个答案:

答案 0 :(得分:9)

据我所知,这里有两个问题:

  • 您没有response属性来反序列化
  • “token:123 id:191”部分实际上只是一个字符串 - 外部token属性的值

因此,如果您将代码更改为:

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

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

那么你最终会得到:

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

如果你想反序列化令牌/ id部分,你可以用:

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

然后打印:

{ token = 123, id = 191 }

答案 1 :(得分:0)

availableVideoPixelFormatTypes