自定义json转换器json.net

时间:2015-04-09 15:30:41

标签: c# json serialization

我正在尝试反序列化一个复杂的JSON对象,并且“JsonSerializer()。反序列化”dosent在这个特定对象Link to this problem上运行良好。现在我正在尝试进行自定义反序列化,因为我不熟悉C#或JSON格式,所以我陷入困境。 请帮我。 JSON数据的示例:

    {"stationary_osbtacles": [
    {
      "latitude": 33.83320,
      "longitude": 33.83320,
      "cylinder_radius": 33.83320,
      "cylinder_height": 33.83320
    }
  ],
  "moving_obstacles": [
    {
      "latitude": 33.83320,
      "longitude": 33.83320,
      "altitude_msl": 33.83320,
      "sphere_radius": 33.83320
    }
  ]}

编辑:以下是我从服务器获取的JSON数据的示例 enter image description here

和一个真实的文本文件,例如:

{“stationary_obstacles”:[{“latitude”:20.0,“cylinder_height”:4323.0,“cylinder_radius”:345.0,“经度”:20.0}],“moving_obstacles”:[{“纬度”:20.0,“sphere_radius “:50.0,”altitude_msl“:100.0,”经度“:20.0},{”纬度“:35.0,”sphere_radius“:453.0,”altitude_msl“:45345.0,”经度“:35.0},{”纬度“:0.0, “sphere_radius”:3242.0,“altitude_msl”:0.14,“经度”:0.0}]}

1 个答案:

答案 0 :(得分:0)

我已经回答了这个问题here。现在你刚刚将JSON中的一些值从int更改为float。我将通过微小的更改粘贴现有答案中的代码。

编辑:您无需手动创建模型。有许多选项可以根据您的JSON生成它们。例如:

  • Visual Studio 。如果您将JSON复制到剪贴板并在Visual Studio click EDIT -> Paste Special -> Paste JSON as Classes中,它将为您生成类结构。
  • json2csharp.com。基于Web的工具,用于生成类 JSON。

这些模型是使用json2csharp.com

生成的
public class StationaryObstacle
{
    public double latitude { get; set; }
    public double cylinder_height { get; set; }
    public double cylinder_radius { get; set; }
    public double longitude { get; set; }
}

public class MovingObstacle
{
    public double latitude { get; set; }
    public double sphere_radius { get; set; }
    public double altitude_msl { get; set; }
    public double longitude { get; set; }
}

public class RootObject
{
    public List<StationaryObstacle> stationary_obstacles { get; set; }
    public List<MovingObstacle> moving_obstacles { get; set; }
}

使用JSON.NET进行反序列化:

var json = "{\"stationary_obstacles\":[{\"latitude\":20.0,\"cylinder_height\":4323.0,\"cylinder_radius\":345.0,\"longitude\":20.0}],\"moving_obstacles\":[{\"latitude\":20.0,\"sphere_radius\":50.0,\"altitude_msl\":100.0,\"longitude\":20.0},{\"latitude\":35.0,\"sphere_radius\":453.0,\"altitude_msl\":45345.0,\"longitude\":35.0},{\"latitude\":0.0,\"sphere_radius\":3242.0,\"altitude_msl\":0.14,\"longitude\":0.0}]}";

// Option 1
var d1 = JsonConvert.DeserializeObject<RootObject>(json);

// Option 2
using (var stringReader = new StringReader(json))
{
    var d2 = (RootObject)new JsonSerializer().Deserialize(stringReader, typeof(RootObject));
}