我有解析给定的JSON数据这个奇怪的问题。我有这样的JSON结构:Newtonsoft JSON.NET解析到自定义键/值对对象的数组
{"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 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 {"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'."}
我做错了什么?谢谢您的回答。
在Visual Studio中,您可以编辑 - >选择性粘贴 - >将JSON粘贴为类,然后DeserializeObject(stringData)。 –
crashmstr
这不是一个数组,它是一个最糟糕的词典,但是您应该能够声明一个Address类,其中的属性与JSON键相同,并直接进行反序列化。 @crashmstr的评论可能适用于较新版本的VS,但创建目标类也是一种选择。 – Eris
我忘了补充说,但保存在字典中的数据也不工作。我将编辑我的问题:-) –