将自定义JSon转换为C#对象

3

我从第三方API获取到JSON,但是它与我的类不匹配。

一些JSON属性无法转换,其他属性名称也不同等等。

我该如何将JSON自定义转换为我的C#对象。

这些是我在C#中拥有的对象:

public class PropertyList {
  public Int32 Page { get; set; }
  public String[] ErrorMessages { get; set; }
  public List<Property> Properties { get; set; }
}

public class Property {
  public String Name { get; set; }
  public String Reference { get; set; }
  public String Region { get; set; }
  public IList<String> Features { get; set; }
  public String Id { get; set; }
  public Double Price { get; set; }
  public IList<String> ImagesUrls { get; set; }
}

这是我想转换的JSon数据:

{
  "page" : 0,
  "errorMessages" : [ ],
  "listings" : [ 
    {
      "data" : {
        "name" : "The name",
        "reference__c" : "ref1234",
        "region__c" : "London",
        "features__c" : "Garage;Garden;",
        "id" : "id1234",
        "price_pb__c" : 700000,
      },
      "media" : {
        "images" : [ 
          {
            "title" : "image1",
            "url" : "http://www.domain.com/image1"
          }, 
          {
            "title" : "image2",
            "url" : "http://www.domain.com/image2"
          }
        ]
      }
    }
    {
      NOTE: Other items
    }
  ]
}

我该如何做到这一点?

更新1

使用Thiago的建议,我能够解析页面(Page)和错误消息(ErrorMessages),但无法处理属性(Properties)。因此,我创建了以下转换器:

public class PropertyResultConverter : JsonConverter {

  public override bool CanConvert(Type objectType) {
    return (objectType == typeof(PropertyResult));
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {

    JObject jo = JObject.Load(reader);
    PropertyResult propertyResult = jo.ToObject<PropertyResult>();
    propertyResult.Properties = jo.SelectToken("listings.data").ToObject<List<Property>>();
    return propertyResult;

  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
    throw new NotImplementedException();
  }

}

当我尝试这样做时,我遇到了以下错误: 发生了类型为“System.NullReferenceException”的异常
在:
propertyResult.Properties = jo.SelectToken("listings.data").ToObject<List<Property>>();

有任何想法为什么会发生这种情况吗?

我的更新有用吗? - Thiago Avelino
1个回答

1

米格尔,你尝试过 http://www.newtonsoft.com/json 吗?

您可以使用C#属性来进行代码映射,如下面的代码片段。

public class PropertyList {
  [JsonProperty("page")]
  public Int32 Page { get; set; }
  [JsonProperty("errorMessages")]
   public String[] ErrorMessages { get; set; }
  [JsonProperty("listings")]
   public List<Property> Properties { get; set; }
}
public class Property {
  [JsonProperty("name")]
  public String Name { get; set; }
  [JsonProperty("reference__c")]
  public String Reference { get; set; }
  [JsonProperty("region__c")]
  public String Region { get; set; }
  [JsonProperty("features__c")]
  public IList<String> Features { get; set; }
  [JsonProperty("id")]
  public String Id { get; set; }
  [JsonProperty("price_pb__c")]
  public Double Price { get; set; }
  [JsonProperty("media")]
  public IList<String> ImagesUrls { get; set; }
}

我不确定 IList 是否能按照你的期望工作。我认为你需要将其适应为 Dictionary。

你可以查看 API: http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

更新

尝试使用以下代码片段解析 'data':

JObject jsonObject = JObject.Parse(json);
            IList<JToken> results = jsonObject["listings"]["data"].Children().ToList();

            IList<Property> processedList = new List<Property>();
            foreach (JToken item in results)
            {
                Property propertyItem = JsonConvert.DeserializeObject<Property>(item.ToString());
                processedList.Add(propertyItem);
            }

我运行了那段代码,它能够正常工作。您可以在我的Github上查看我生成的代码:

https://github.com/thiagoavelino/VisualStudio_C/blob/master/VisualStudio_C/StackOverFlow/ParsingJason/ParsingJson.cs


我尝试了你的建议,但是在解析属性方面仍然存在问题。然后我尝试了自定义转换器,但没有成功。我刚刚添加了一个更新。你知道可能出了什么问题吗? - Miguel Moura
Miguel,我正在尝试这个,很快就会发布答案。 - Thiago Avelino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接