8

I have a problem with deserializing a Json-string to an object.

This is a sample json i receive from a webservice:

{
    "GetDataResult":
                 "{
                     \"id\":1234,
                     \"cityname\":\"New York\",
                     \"temperature\":300,
                  }"
}

And I have a class CityData that looks like this

[JsonObject("GetDataResult")]
public class CityData
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("cityname")]
    public string CityName { get; set; }

    [JsonProperty("temperature")]
    public int Temperature { get; set; }
}

I try to deserialize the json with a call of the method DeserializeObject

var cityData = JsonConvert.DeserializeObject<CityData>(response);

but the root element seems to make problems...

Do you guys know how I can fix it, so that I receive a CityData-object with the data filled in?

Liam
  • 27,717
  • 28
  • 128
  • 190
xeraphim
  • 4,375
  • 9
  • 54
  • 102
  • What is `response`? The value of the `GetDataResult` property in your JSON is a string, so that's not going to deserialize to the properties the way you expect. – NathanAldenSr Mar 14 '14 at 16:30
  • The web service is spitting up bad JSON. It's technically legal, but obviously not what you want. The escaped string quotes in there...it's all bad. – djcrabhat Mar 14 '14 at 16:34
  • Chances are he's using WCF's terrible "wrapping" of the JSON, or something like that. – NathanAldenSr Mar 14 '14 at 16:38

1 Answers1

15

The json response contains an object that within itself contains a json string representing the data result.

You need to deserialize twice, once for the response and one more for the data result.

var response = JsonConvert.DeserializeObject<JObject>(responseStr);
var dataResult = (string)response["GetDataResult"];
var cityData = JsonConvert.DeserializeObject<CityData>(dataResult);
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • You can avoid deserialize twice, if you write custom `JsonConverter` and use `LINQ to JSON`. – Ilija Dimov Mar 14 '14 at 17:39
  • 1
    Of course, but then you'd have to write the converter. This will be the simplest fix for this, at least until he'd need a more robust solution. – Jeff Mercado Mar 14 '14 at 18:17
  • 3
    Cast to string is throwing an error. I used ToString() instead – Roman Gudkov Jul 05 '17 at 14:31
  • @RomanGudkov, apparently your data is not a string, it's probably an object already. Just cast to a `JObject` or whatever the appropriate type it is. There's no sense in reparsing it if you don't have to. – Jeff Mercado Jul 05 '17 at 14:56