您好,我在反序列化IRestResponse.Content JSON响应时遇到问题。
{
"49":
{
"9345": "2018-10-11",
"106": null,
"107": "4222238842",
"108": "CompanyName",
"8210": "2018-11-11/1",
"110": "00-300",
"109": "Street",
"112": "Country",
"18418": null,
"18420": "S\u0141ON",
"18422": "OtherString",
"9338": null,
"111": "City"
}
}
我尝试了一些网页或内置的VisualStudio转换器,但它给了我类似的东西。
public class Rootobject
{
public _49 _49 { get; set; }
}
public class _49
{
public string _9345 { get; set; }
public object _106 { get; set; }
public string _107 { get; set; }
public string _108 { get; set; }
public string _8210 { get; set; }
public string _110 { get; set; }
public string _109 { get; set; }
public string _112 { get; set; }
public object _18418 { get; set; }
public string _18420 { get; set; }
public string _18422 { get; set; }
public object _9338 { get; set; }
public string _111 { get; set; }
}
看起来不错,但就我而言,这些JSON文件具有动态属性名称,并且可以具有另一个“ int”值。同样,“ 49”内的嵌套内容可以具有更少或更多的值。 我对收集“ 49” <<此值存储到变量特别感兴趣。
我也尝试过类似的方法,但是也不起作用:
public class DeserializeJsonContent
{
public Dictionary<object, Dictionary<object, object>> values { get; set; }
}
简化的代码示例
public List<T> JSONDeserialize<T>(IRestResponse response) where T : new()
{
var responseData = client.Deserialize<List<T>>(response);
var ListDeserializedData = responseData.Data.ToList<T>();
return ListDeserializedData;
}
....
var response = rest.client.Execute(request);
if (response.IsSuccessful)
{
var obj = rest.JSONDeserialize<DeserializeJsonContent>(response);
}
obj的计数为1,但vals = null
解决后编辑: 我仍然不知道为什么我的反序列化类在这种情况下不起作用(我在许多其他json反序列化响应中使用它) 感谢xdtTransform的回答,我已经尝试了所有这些方法
var obj2 = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<object, object>>>(response.Content);
var obj3 = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(response.Content);
var obj4 = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<string, string>>>(response.Content);
var obj5 = JsonConvert.DeserializeObject<Dictionary<object, Dictionary<string, string>>>(response.Content);
var obj6 = JsonConvert.DeserializeObject<Dictionary<object, Dictionary<object, object>>>(response.Content);
var obj7 = JsonConvert.DeserializeObject<Dictionary<object, Dictionary<int, object>>>(response.Content);
然后就
var value = obj2.First().Key;
答案 0 :(得分:2)
使用Newtonsoft.Json,您可以像这样直接将反序列化为Dictionary<string,Dictionary<string,string>>
:
var obj = JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string,string>>>(input);
如果您需要将其设置为自定义类型,则应将其声明为:
public class WrapperType : Dictionary<string,Dictionary<string,string>>{}
然后反序列化保持不变:
var obj = JsonConvert.DeserializeObject<WrapperType>(input);
答案 1 :(得分:0)
请反序列化响应内容
string data = response.Content;
var responseData = client.Deserialize<List<T>>(data);