Newtonsoft json反序列化问题 [英] Newtonsoft json deserialisation problem

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

问题描述





你能协助如何反序化下面的Json字符串吗?



 string JsonString = @{'api_res_key':'TestKey','res_status':'200','res_data':{'32':{'state_id':'32','state_name':' ANDAMAN& NICOBAR'},'1':{'state_id':'1','state_name':'ANDHRA PRADESH'},'3':{'state_id':'3','state_name':'ARUNACHAL PRADESH }}}; 
JObject person = JObject.Parse(JsonString);

我尝试了什么:

我曾尝试以下列方式进行反序列化,但它给了我例外...


< pre> public class RootObject
{
public string api_res_key {get;组; }
public string res_status {get;组; }
public ResData [] res_data {get;组; }
}

公共类ResData
{
public string state_id {get;组; }
public string state_name {get;组; }
}





 var Data = JsonConvert.DeserializeObject< RootObject []>(JsonString) ; 

解决方案

您遇到问题的原因是您无法将字典反序列化为列表。



当您查看JSON'res_data'对象时,有3组密钥和&价值对:

'32':{'state_id':'32','state_name':'ANDAMAN& NICOBAR'},
'1':{'state_id':'1','state_name':'ANDHRA PRADESH'},
'3':{'state_id':'3','state_name ':'ARUNACHAL PRADESH'}





所以要修复,你需要做类似的事情:

< pre lang =c#> public class 状态
{
[JsonProperty( state_id)]
public 字符串 StateId { get ; set ; }

[JsonProperty( state_name)]
< span class =code-keyword> public string StateName { get ; set ; }
}

public class RootObject
{
[JsonProperty( api_res_key)]
public string ApiResKey { get ; set ; }

[JsonProperty( res_status)]
< span class =code-keyword> public string ResStatus { get ; set ; }

[JsonProperty( res_data)]
< span class =code-keyword> public Dictionary< int,State> ResData { get ; set ; }
}



然后你可以反序列化JSON:

  var  data = JsonHelper.ToClass< RootObject>(JsonString); 



这里是本文的助手类:在C#中使用JSON& VB [ ^ ]

  public   static   class  JsonHelper 
{
public static string FromClass< T>(T data, bool isEmptyToNull = false
JsonSerializerSettings jsonSettings = null
{
string response = string .Empty;

if (!EqualityComparer< T> .Default.Equals(data, default (T)))
response = JsonConvert.SerializeObject(data,jsonSettings);

return isEmptyToNull? (response == {} null:response):response;
}

public static T ToClass< T>(< span class =code-keyword> string data,JsonSerializerSettings jsonSettings = null
{
var response = default (T);

if (!string.IsNullOrEmpty(data))
response = jsonSettings == null
? JsonConvert.DeserializeObject< T>(data)
:JsonConvert.DeserializeObject< T>(data,jsonSettings);

return 响应;
}
}


Hi,

Can you please assist how to deserialise the below Json string?

string JsonString = @"{'api_res_key':'TestKey','res_status':'200','res_data':{'32':{ 'state_id':'32','state_name':'ANDAMAN & NICOBAR'},'1':{ 'state_id':'1','state_name':'ANDHRA PRADESH'},'3':{ 'state_id':'3','state_name':'ARUNACHAL PRADESH'}}}";
            JObject person = JObject.Parse(JsonString);

What I have tried:

I had tried to deserialise in following way but it gives me exception...


<pre>    public class RootObject
    {
        public string api_res_key { get; set; }
        public string res_status { get; set; }
        public ResData[] res_data { get; set; }
    }

    public class ResData
    {
        public string state_id { get; set; }
        public string state_name { get; set; }
    }



var Data = JsonConvert.DeserializeObject<RootObject[]>(JsonString);

解决方案

The reason that you're having problems is that you can't deserialize a Dictionary into a List.

When you look at the JSON 'res_data' object, there are 3 sets of key & value pairs:

'32':{ 'state_id':'32','state_name':'ANDAMAN & NICOBAR'},
'1' :{ 'state_id':'1','state_name':'ANDHRA PRADESH'},
'3' :{ 'state_id':'3','state_name':'ARUNACHAL PRADESH'}



So to fix, You need to do something like:

public class State
{
    [JsonProperty("state_id")]
    public string StateId { get; set; }

    [JsonProperty("state_name")]
    public string StateName { get; set; }
}

public class RootObject
{
    [JsonProperty("api_res_key")]
    public string ApiResKey { get; set; }

    [JsonProperty("res_status")]
    public string ResStatus { get; set; }

    [JsonProperty("res_data")]
    public Dictionary<int, State> ResData { get; set; }
}


Then you can deserialize the JSON:

var data = JsonHelper.ToClass<RootObject>(JsonString);


And here is the helper class from this article: Working with JSON in C# & VB[^]

public static class JsonHelper
{
    public static string FromClass<T>(T data, bool isEmptyToNull = false,
                                        JsonSerializerSettings jsonSettings = null)
    {
        string response = string.Empty;

        if (!EqualityComparer<T>.Default.Equals(data, default(T)))
            response = JsonConvert.SerializeObject(data, jsonSettings);

        return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
    }

    public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
    {
        var response = default(T);

        if (!string.IsNullOrEmpty(data))
            response = jsonSettings == null
                ? JsonConvert.DeserializeObject<T>(data)
                : JsonConvert.DeserializeObject<T>(data, jsonSettings);

        return response;
    }
}


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

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