Deserializing nested JSON structure to a flattened class with Json.NET using annotations

前端 未结 3 1427
面向向阳花
面向向阳花 2020-12-17 08:52

Is it possible to use JsonProperty annotation to map a nested Json property to a non-nested .NET member? Say you\'ve got some Json like this:

{
     \"id\":9         


        
3条回答
  •  长情又很酷
    2020-12-17 09:23

    For really complex JSON Situations I really like the manual mapping approach Demis Bellot has taken with ServiceStack.Text. This allows me to pass an httpResponse.Content to a JsonConverter.Convert(string json) method.

    This has the added benefit of keeping your model objects squeaky clean.

    var place = JsonObject.Parse(JsonCentroid)
    .Object("place")
    .ConvertTo(x => new Place
    {
        WoeId = x.Get("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)
                }),
    });
    

    You can see the full test here.

提交回复
热议问题