Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize JSON containing delimited JSON?

Tags:

c#

json.net

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?

like image 445
xeraphim Avatar asked Mar 14 '14 16:03

xeraphim


People also ask

How do I deserialize a JSON file?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JsonSerializer deserialize?

Serialization and deserialization in . NET application, JSON data format conversion to . NET objects and vice versa is very common. Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.

What is Serialised JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


1 Answers

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);
like image 156
Jeff Mercado Avatar answered Oct 17 '22 12:10

Jeff Mercado