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

时间:2019-05-23 23:19:58

标签: c# json json.net openstreetmap json-deserialization

如果我有这个JSON,其中有一个带有标签versiongeneratorom3selements的标头。 elements的类型可以为nodeway,并且相关的JSON密钥随类型而异。我正在尝试使用JsonSubTypes将每种元素类型转换为C#类。

示例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; }
    }
}

哪个返回:

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

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

问题

我可以正确构造类OSMdata吗?我认为我正确地遵循了这些示例,但是不确定是否正确地将类NodeEdge分配给父类OSMdata

解串器如何知道将标签"tiger:cfcc"分配给Cfcc中的EdgeTags属性?

2 个答案:

答案 0 :(得分:1)

声明您的课程,如下所示:


    // 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

答案 1 :(得分:0)

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

使用类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);
}

在我提出的问题中,第二个仍然有意义。

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

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

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