在 C# 中反序列化 Open Street Map JSON

Deserialize Open Street Map JSON in C#

如果我有这个 JSON,其中有一个带有标签 versiongeneratorom3selements 的 header。 elements 可以是 nodeway 类型,关联的 JSON 键因类型而异。我正在尝试使用 JsonSubTypes 将每个元素类型转换为 C# class。

示例JSON:

[
  {
    "version": 0.6,
    "generator": "Overpass API 0.7.55.7 8b86ff77",
    "osm3s": {
      "timestamp_osm_base": "2019-05-21T18:03:02Z",
      "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
    },
    "elements": [
      {
        "type": "node",
        "id": 4949106384,
        "lat": 32.2686857,
        "lon": -107.738218,
        "tags": {
          "highway": "turning_circle"
        }
      },
      {
        "type": "way",
        "id": 14527404,
        "nodes": [
          142882281,
          3048075541,
          1598998260
        ],
        "tags": {
          "highway": "residential",
          "name": "West Apple Street",
          "tiger:cfcc": "A41",
          "tiger:county": "Luna, NM",
          "tiger:name_base": "Apple",
          "tiger:name_direction_prefix": "W",
          "tiger:name_type": "St",
          "tiger:reviewed": "no"
        }
      }
    ]
  }
]

我正在尝试使用以下方法对其进行反序列化:

var json = JsonConvert.DeserializeObject<OSMdata>(jsonText);

其中 OSMdata 看起来像:

[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubType(typeof(Element.Node), "node")]
[JsonSubtypes.KnownSubType(typeof(Element.Edge), "way")]

public abstract class OSMdata
{
    public float version { get; set; }
    public string generator { get; set; }
    public Osm3s osm3s { get; set; }
    public Element[] elements { get; set; }
}

public class Osm3s : OSMdata
{
    public DateTime timestamp_osm_base { get; set; }
    public string copyright { get; set; }
}

public class Element : OSMdata
{
    public class Node : Element
    {
        public string type { get; } = "node";
        public long id { get; set; }
        public float lat { get; set; }
        public float lon { get; set; }
        public NodeTags tags { get; set; }
    }

    public class NodeTags : Node
    {
        public string highway { get; set; }
        public string _ref { get; set; }
    }

    public class Edge : Element
    {
        public string type { get; } = "way";
        public long id { get; set; }
        public long[] nodes { get; set; }
        public EdgeTags tags { get; set; }
    }

    public class EdgeTags : Edge
    {
        public string highway { get; set; }
        public string name { get; set; }
        public string cfcc { get; set; }
        public string county { get; set; }
        public string oneway { get; set; }
    }
}

哪个returns:

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   at JsonSubTypes.JsonSubtypes.CreateCompatibleList(Type targetContainerType, Type elementType)
   at JsonSubTypes.JsonSubtypes.ReadArray(JsonReader reader, Type targetType, JsonSerializer serializer)
   at JsonSubTypes.JsonSubtypes.ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at newapp.Program.Main(String[] args) in C:\Users\RDCRLDDH\source\repos\newapp\newapp\Program.cs:line 23

虽然我不明白这个错误并正在寻找解决方案,但我想澄清以下几个问题:

问题

我是否正确构建了 class OSMdata?我想我正确地遵循了示例,但不确定我是否正确地将 classes NodeEdge 分配给 parent class OSMdata.

反序列化器如何知道将标记 "tiger:cfcc" 分配给 EdgeTags 中的 Cfcc 属性?

我不知道如何直接从 JSON 反序列化,但找到了一个合适的解决方法,将 JSON 转换为 JArray 并遍历每个元素并转换为由节点和边组成的 C# class。

使用 class Element:

    [JsonConverter(typeof(JsonSubtypes), "type")]
    [JsonSubtypes.KnownSubType(typeof(Element.Node), "node")]
    [JsonSubtypes.KnownSubType(typeof(Element.Edge), "way")]

    public class Element
    {
        public class Node : Element

        {
            public string type { get; } = "node";
            public long id { get; set; }
            public float lat { get; set; }
            public float lon { get; set; }
            public NodeTags tags { get; set; }
        }

    public class NodeTags : Node
    {
        public string highway { get; set; }
        public string _ref { get; set; }
    }

    public class Edge : Element
    {
        public string type { get; } = "way";
        public long id { get; set; }
        public long[] nodes { get; set; }
        public EdgeTags tags { get; set; }
    }

    public class EdgeTags : Edge
    {
        [JsonProperty("highway")]
        public string Highway { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }


        [JsonProperty("tiger:cfcc")]
        public string cfcc { get; set; }

        [JsonProperty("tiger:county")]
        public string County { get; set; }

        [JsonProperty("oneway")]
        public string Oneway { get; set; }
    }

您可以 json 使用以下方法解析:

JArray jsonSearch = JArray.Parse(jsonText);

然后您可以使用以下方法创建包含每个元素的列表:

IList<JToken> results = jsonSearch[0]["elements"].Children().ToList();

然后您可以遍历 results 并使用以下方法将数据转换为 C# 对象:

var element_list = new List<Element>();

foreach (JObject element in results)
{
    Element myelement = element.ToObject<Element>();
    element_list.Add(myelement);
}

在我提出的问题中,第二个问题仍然相关。

在 class 中创建 属性 名称之前,您可以使用 JsonProperty 将名称无效的 属性 分配给 C# class。

[JsonProperty("tiger:cfcc")]
public string cfcc { get; set; }

感谢@dbc 和其他有用的评论为我指明了正确的方向!

声明您的 类 如下:


    // no longer abstract
    public class OSMdata
    {
        public float version { get; set; }
        public string generator { get; set; }
        public Osm3s osm3s { get; set; }

        // for arrays or collection this line must be present here
        [JsonConverter(typeof(JsonSubtypes), "type")]
        public Element[] elements { get; set; }
    }

    // no need to inherits from OSMData
    public class Osm3s
    {
        public DateTime timestamp_osm_base { get; set; }
        public string copyright { get; set; }
    }


    [JsonConverter(typeof(JsonSubtypes), "type")]
    [JsonSubtypes.KnownSubType(typeof(Node), "node")]
    [JsonSubtypes.KnownSubType(typeof(Edge), "way")]
    public abstract class Element : OSMdata
    {
        public abstract string type { get; }
    }

    public class Node : Element
    {
        public override string type { get; } = "node";
        public long id { get; set; }
        public float lat { get; set; }
        public float lon { get; set; }
        public NodeTags tags { get; set; }
    }

    public class NodeTags
    {
        public string highway { get; set; }
        public string _ref { get; set; }
    }

    public class Edge : Element
    {
        public override string type { get; } = "way";
        public long id { get; set; }
        public long[] nodes { get; set; }
        public EdgeTags tags { get; set; }
    }

    public class EdgeTags
    {
        public string highway { get; set; }
        public string name { get; set; }
        public string cfcc { get; set; }
        public string county { get; set; }
        public string oneway { get; set; }
    }

并反序列化为:

var json = JsonConvert.DeserializeObject<OSMdata>(jsonText);

参见 运行 示例:https://dotnetfiddle.net/pdJ0ab