Json C#:反序列化不断变化的内容或json响应

时间:2011-02-20 14:43:35

标签: c# json deserialization

我使用的Api不是每次都根据需要返回相同的响应。有些地方有更多细节,有些内容有更多属性,其他。生成的序列化对象每次都不相同,导致不匹配时反序列化错误。此项目的对象与整个内容响应不匹配,但只与此内容中的一部分相符:Centroid。

{
   "place":{
      "woeid":12345,
      "placeTypeName":"State",
      "placeTypeName attrs":{
         "code":8
      },
      "name":"My Region",
      "country":"",
      "country attrs":{
         "type":"Country",
         "code":"XX"
      },
      "admin1":"My Region",
      "admin1 attrs":{
         "type":"Region",
         "code":""
      },
      "admin2":"",
      "admin3":"",
      "locality1":"",
      "locality2":"",
      "postal":"",
      "centroid":{
         "latitude":30.12345,
         "longitude":40.761292
      },
      "boundingBox":{
         "southWest":{
            "latitude":32.2799,
            "longitude":50.715958
         },
         "northEast":{
            "latitude":29.024891,
            "longitude":12.1234
         }
      },
      "areaRank":10,
      "popRank":0,
      "uri":"http:\/\/where.yahooapis.com",
      "lang":"en-US"
   }
}

有人可以指出最好的方法来反序列化一段内容而不是完整的响应(质心不在同一个地方),或反序列化不断变化的响应模式。

我使用ServiceStack C#serializer但欢迎所有提议。感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用 DataContractJsonSerializer ,它是标准.NET框架的一部分。您只需定义您感兴趣的属性。其他属性将被忽略。

class CentroidReader
{
    public static Centroid ReadControid(Stream stream)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Response));
        Response response = serializer.ReadObject(stream) as Response;
        return response.Place.Centroid;
    }
}

[DataContract]
class Response
{
    [DataMember(Name = "place")]
    public Place Place { get; set; }
}

[DataContract]
class Place
{
    [DataMember(Name = "centroid")]
    public Centroid Centroid { get; set; }
}

[DataContract]
class Centroid
{
    [DataMember(Name = "latitude")]
    public double? Latitude { get; set; }
    [DataMember(Name = "longitude")]
    public double? Longitude { get; set; }
}

答案 1 :(得分:1)

实际上有几种方法可以使用ServiceStack的JsonSerializer解析它,如example of parsing one of GitHub's JSON API所示。

我会采用 JsonObject 方法,因为你最终得到了你选择的C#类,尽管它需要的不仅仅是你习惯使用ServiceStack的JsonSerializer的1-liner。无论如何这里是结果代码:

Func<JsonObject, Centroid> toCentroid = map => 
    new Centroid(map.Get<decimal>("latitude"), map.Get<decimal>("longitude"));

var place = JsonObject.Parse(JsonCentroid)
    .Object("place")
    .ConvertTo(x => new Place
    {
        WoeId = x.Get<int>("woeid"),
        PlaceTypeName = x.Get(""),
        PlaceTypeNameAttrs = x.Object("placeTypeName attrs"),
        Name = x.Get("Name"),
        Country = x.Get("Country"),
        CountryAttrs = x.Object("country attrs"),
        Admin1 = x.Get("admin1"),
        Admin1Attrs = x.Object("admin1 attrs"),
        Admin2 = x.Get("admin2"),
        Admin3 = x.Get("admin3"),
        Locality1 = x.Get("locality1"),
        Locality2 = x.Get("locality2"),
        Postal = x.Get("postal"),

        Centroid = x.Object("centroid")
            .ConvertTo(toCentroid),

        BoundingBox = x.Object("boundingBox")
            .ConvertTo(y => new BoundingBox
            {
                SouthWest = y.Object("southWest").ConvertTo(toCentroid),
                NorthEast = y.Object("northEast").ConvertTo(toCentroid)
            }),

        AreaRank = x.Get<int>("areaRank"),
        PopRank = x.Get<int>("popRank"),
        Uri = x.Get("uri"),
        Lang = x.Get("lang"),
    });

这是full source code of this example