我在解析给定的 JSON 数据时遇到了这个奇怪的问题。我有这个 JSON 结构:
{"value":[
{"street":"Karlova 25"},
{"city":"Prague"},
{"gpsLat":"50.1571"},
{"gpsLon":"15.0482"}
]}
如何使用 Newtonsoft JSON.NET 库解析此结构?我尝试使用自己的 JsonConverter 类:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer){
JArray jarray = (JArray)((JTokenReader)reader).CurrentToken;
List<AddressValue> values = new List<AddressValue>();
foreach (var jobj in jarray.Children<JObject>()){
foreach (JProperty prop in jobj.Properties()){
values.Add(new AddressValue() { Label = prop.Name, Value = prop.Value.ToString() });
}
}
return values.ToArray();
}
class AddressValue{
public string Label { get; set; }
public string Value { get; set; }
}
但我有一个异常(exception):
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.DLL
Additional information: Unexpected token when deserializing object: StartObject. Path 'value[0]'.
编辑: 我还尝试将其保存到字典中:
[JsonProperty(PropertyName = "value")]
public Dictionary<string, string> Value{get; set;}
但我有另一个异常(exception):
$exception {"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath 'param.value'."}
我做错了什么?谢谢您的回答。
最佳答案
您不需要重新发明轮子。该功能已经可以使用了。 创建如下所示的类:
public class Value
{
public string street { get; set; }
public string city { get; set; }
public string gpsLat { get; set; }
public string gpsLon { get; set; }
}
public class MyClass
{
public List<Value> value { get; set; }
}
现在您可以简单地将 json 反序列化为 poco 对象。
MyClass result = JsonConvert.DeserializeObject<MyClass>(youJson);
关于c# - Newtonsoft JSON.NET 解析为自定义键/值对对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33552322/