【问题标题】:Deserialize json array in Xamarin [duplicate]在Xamarin中反序列化json数组[重复]
【发布时间】:2021-12-31 16:48:32
【问题描述】:

我想在我的 Xamarin android 应用程序中反序列化这个 json 文件以仅获取坐标。

{
"type": "FeatureCollection",
"features": [
    {
        "type": "Feature",
        "id": "6849033",
        "geometry": {
            "type": "MultiPolygon",
            "coordinates": [
                [
                    [
                        [
                            6.562265,
                            40.36426
                        ],
                        [
                            6.5622743,
                            40.3642745
                        ],
                        [
                            6.5622944,
                            40.3642897
                        ],etc...

这是我上课的方法

    public class Cadastre
{
    
    public List<List<List<List<float>>>> coordinates { get; set; }

    public Cadastre()
    {

    }

}

最后是我的代码来反序列化我的 json 文件

        string responseFinished = await GetJson();

        Cadastre c = JsonConvert.DeserializeObject<Cadastre>(responseFinished);

我尝试了许多解决方案,但我的坐标仍然为空。 如果有人有解决方案或线索,我将不胜感激。

【问题讨论】:

  • 您缺少几层外部容器模型public class Root public List&lt;Feature&gt; features { get; set; } }public class Feature { public Cadastre geometry { get; set; } }。将您的 JSON 复制到 json2csharp.com 或来自 How to auto-generate a C# class file from a JSON string 的任何其他工具,您应该获得正确的包装器类型。事实上,我认为你的问题可以作为一个副本结束,同意吗?
  • 谢谢你的评论对我有很大帮助,现在它的工作!

标签: c# json json.net


【解决方案1】:

试试这个

var jsonObject=JObject.Parse(json);

var coordinates = ((JArray)jsonObject["features"][0]["geometry"]["coordinates"][0][0]).Select(c => new { One = c[0], Two = c[1]}).ToList();

结果

[
  {
    "One": 6.562265,
    "Two": 40.36426
  },
  {
    "One": 6.5622743,
    "Two": 40.3642745
  },
  {
    "One": 6.5622944,
    "Two": 40.3642897
  }
]

或者如果你想反序列化你的方式

List<List<List<List<float>>>> coordinates = ((JArray)jsonObject["features"][0]["geometry"]["coordinates"]).ToObject<List<List<List<List<float>>>>>();

结果

[
  [
    [
      [
        6.562265,
        40.36426
      ],
      [
        6.5622745,
        40.364273
      ],
      [
        6.5622945,
        40.36429
      ]
    ]
  ]
]

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多