反序列化JSON偏 [英] Deserialize partial JSON

查看:156
本文介绍了反序列化JSON偏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有反序列化的JSON字符串对象问题



这是一个简单的JSON我从一个web服务获得:

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

和我有一个类CityData看起来像这样

  [JSONObject的(GetDataResult)] 
公共类CityData
{
[JsonProperty(ID)]
公众诠释标识{搞定;组; }

[JsonProperty(城市名)]
公共字符串CITYNAME {搞定;组; }

[JsonProperty(温度)]
公众诠释温度{搞定;组; }
}



我尝试用方法DeserializeObject <的呼叫反序列化JSON / p>

  VAR cityData = JsonConvert.DeserializeObject< cityData>(响应); 



但根元素似乎使问题...



难道你们知道我怎么能解决这个问题,让我得到一个CityData对象已填充?


解决方案

JSON响应包含中本身就含有表示数据结果的JSON字符串的对象。



您需要反序列化两次,一次为响应和多一个对于该数据的结果。

  VAR响应= JsonConvert.DeserializeObject< JObject>(responseStr); 
VAR dataResult =(字符串)响应[GetDataResult];
VAR cityData = JsonConvert.DeserializeObject< CityData>(dataResult);


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?

解决方案

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

这篇关于反序列化JSON偏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆