使用注释使用Json.NET将嵌套的JSON结构反序列化为展平类

jul*_*jul 24 c# asp.net json json.net

是否可以使用JsonProperty批注将嵌套的Json属性映射到非嵌套的.NET成员?说你有一些这样的Json:

{
     "id":9999,
     "created_date":"Thu, 23 Jun 2011 12:56:24 +0000",
     "pos":{
        "type":"someType",
        "coordinates":[
           59.323,
           18.0654
        ]
     }
}
Run Code Online (Sandbox Code Playgroud)

并希望将其反序列化为扁平类MyClass使用

JsonConvert.DeserializeObject<MyClass>(jsonstr);
Run Code Online (Sandbox Code Playgroud)

可以使用注释将Json坐标列表映射到下面的类中的Lat和Lng:

public class MyClass {
   [JsonProperty("id")]
   public int Id { get; set; }
   [JsonProperty("created_date")]
   public DateTime Created { get; set; }
   [JsonProperty("????")]
   public float Lat { get; set; }
   [JsonProperty("?????")]
   public float Lng { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

只是好奇.我总是可以像这样定义类,它似乎工作正常:

public class MyClass {
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("date_created")]
    public DateTime Created { get; set; }
    [JsonProperty("pos")]
    public PosClass Pos { get; set; }
}

public class PosClass
{
    public List<float> coordinates { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Anu*_*nuj -1

对于非常复杂的 JSON 情况,我真的很喜欢 Demis Bellot 使用ServiceStack.Text所采用的手动映射方法。这允许我将 httpResponse.Content 传递给 JsonConverter.Convert(string json) 方法。

这样做的另一个好处是可以保持模型对象干净整洁。

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"),
    BoundingBox = x.Object("boundingBox")
            .ConvertTo(y => new BoundingBox
            {        
                    SouthWest = y.Object("southWest").ConvertTo(toCentroid),
                    NorthEast = y.Object("northEast").ConvertTo(toCentroid)
            }),
});
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看完整的测试。