11

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);
xaisoft
  • 3,343
  • 8
  • 44
  • 72

2 Answers2

15

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 }
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Okay so that explains the internalized question I kind of had all along. I've seen the deserializer skip *over* properties if it can find a match. Maybe better stated, I've seen it deserialize into objects that are lower than the root. If I had any more votes for the day you'd have mine; but that doesn't much matter for you probably. I'm sure by an hour in you're out of up votes. :D – Mike Perrenoud Nov 21 '13 at 14:38
  • I got it to work with your that example, but I put a more detailed on that I can't get to work. – xaisoft Nov 21 '13 at 16:54
  • 1
    @xaisoft: Well what's the JSON to go with that? To be honest, I think it may be worth asking as a new question, just to keep everything clearer. – Jon Skeet Nov 21 '13 at 16:57
1
string jsonToken = @"{'response':{'token':{'token':'123','id':191}}}";
var def = new
{
    response = new
    {
        token = new { token = string.Empty, id = 0 }
    }
};

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