gpt4 book ai didi

c# - JSON C# : deserializing a changing content or a piece of json response

转载 作者:太空宇宙 更新时间:2023-11-03 11:39:58 25 4
gpt4 key购买 nike

我使用的 Api 并非每次都根据要求的位置返回相同的响应。有些地方有更多的细节,有些内容比其他地方有更多的属性。生成的序列化对象每次都不相同,导致在不匹配时出现反序列化错误。该项目的对象不是匹配整个内容响应,而是仅匹配此内容的一部分:质心。

{
"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# 序列化器,但欢迎所有建议。谢谢。

最佳答案

实际上有几种方法可以使用 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 .

关于c# - JSON C# : deserializing a changing content or a piece of json response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5057684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com