且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Newtonsoft json反序列化问题

更新时间:2023-02-17 20:16:54

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



当您查看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'}





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

public class 状态
{
[JsonProperty( state_id)]
public 字符串 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 ; }
}



然后你可以反序列化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>( 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;
    }
}