我有来自 API 的 JSON,如下所示:
{
"GetJsonResult": {
"EntityName": "account",
"FailureReason": "",
"Counter": 0,
"MoreRecords": false,
"OptionSetName": "sic_organisationtitlewad",
"Success": true,
"OptionSetsClean": "[{\"Mr\":100000000},{\"Mrs\":100000003},{\"Miss\":100000002},{\"Ms\":100000004},{\"Prof\":100000001},{\"Sir\":907510000}]",
"OptionSets": [
{
"Mr": 100000000
},
{
"Mrs": 100000003
},
{
"Miss": 100000002
},
{
"Ms": 100000004
},
{
"Prof": 100000001
},
{
"Sir": 907510000
}
],
"Entities": null
}
}
我有一个这样的类定义:
public class GetJsonResult
{
[JsonProperty("EntityName")]
public string EntityName { get; set; }
[JsonProperty("FailureReason")]
public string FailureReason { get; set; }
[JsonProperty("Counter")]
public int Counter { get; set; }
[JsonProperty("MoreRecords")]
public bool MoreRecords { get; set; }
[JsonProperty("OptionSetName")]
public string? OptionSetName { get; set; }
[JsonProperty("Success")]
public bool Success { get; set; }
[JsonProperty("OptionSetsClean")]
public Dictionary<string, int>? OptionSetsClean { get; set; }
[JsonProperty("OptionSets")]
public object OptionSets { get; set; }
}
并使用“JsonConvert.DeserializeObject”来处理数据。
我想获取“OptionSetsClean”或“OptionSets”中的数据(它们包含相同的数据)以转换为字典或列表之类的内容。但是,我想不出一种方法来做到这一点。
作为一个选项,您可以使用自定义转换器来转换为列表 如果需要,您可以扩展 ot 并转换为字典。 我把你的 json 存储到文件中。 另外,您还需要再包装一个对象。
void Main()
{
var j = File.ReadAllText("C:\\1\\test.json");
var x = JsonConvert.DeserializeObject<Root>(j).Dump();
}
public class Root
{
public GetJsonResult GetJsonResult { get; set; }
}
public class GetJsonResult
{
public string EntityName { get; set; }
public string FailureReason { get; set; }
public int Counter { get; set; }
public bool MoreRecords { get; set; }
public string OptionSetName { get; set; }
public bool Success { get; set; }
[JsonConverter(typeof(StringConverter<Dictionary<string,int>>))]
public List<JObject> OptionSetsClean { get; set; }
public List<JObject> OptionSets { get; set; }
public string Entities {get;set;}
}
public class StringConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var res = JsonConvert.DeserializeObject<List<JObject>>(reader.Value.ToString());
return res;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
结果