Skip to main content
 首页 » 编程设计

c#之Newtonsoft JSON.NET 解析为自定义键/值对对象数组

2024年02月05日8bjzhanghao

我在解析给定的 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);