Существует проблема с объявлением массива во время сериализации json

#json

Вопрос:

Я получил файл Json с помощью API в c#.

При сериализации данных возникла проблема с arry.

 {  "features":[  {  "geometry":{  "type":"Point",  "coordinates":[  126.0,  37.0  ]  },  },  {  "geometry":{  "type":"LineString",  "coordinates":[  [  126.0,  37.0  ],  [  126.0,  37.0  ]  ]  },  }  ] }  

Это часть файла json. И массив «координат» повторяется, но один одномерный, а другой двумерный. Я не знаю, как об этом заявить. Это мой код. Как я должен объявить класс геометрии?

 public class JsonClass {  public string type { get; set; }  public Listlt;featuresgt; features { get; set; } }  public class features {  public string type { get; set; }  public geometry geometry { get; set; }  public properties properties { get; set; } }    public class geometry {  public string type { get; set; }  public float[] coordinates { get; set; }  //or public float[,] coordinates { get; set; }?  //both error... }  

Пожалуйста, поймите, что я воспользовался переводчиком, потому что не мог говорить по-английски. Спасибо!

Ответ №1:

Попробуйте это, оно было протестировано в VS 2022

 var data = JsonConvert.DeserializeObjectlt;Datagt;(json);   

классы

 public partial class Data {  [JsonProperty("features")]  public Listlt;Featuregt; Features { get; set; } }  public partial class Feature {  [JsonProperty("geometry")]  public Geometry Geometry { get; set; } }  public partial class Geometry {  [JsonProperty("type")]  public string Type { get; set; }   [JsonProperty("coordinates")]  public Listlt;objectgt; _coordinates  {  set  {  if (value != null amp;amp; value.Count gt; 0)  if (double.TryParse(value[0].ToString(), out _))  {  Coordinates1D = value.Select(x =gt; Convert.ToDouble(x)).ToList();  }  else  Coordinates2D = value.Select(x =gt; ((JArray)x).ToObjectlt;Listlt;doublegt;gt;()).ToList();  }  }   public Listlt;doublegt; Coordinates1D { get; set; }    public Listlt;Listlt;doublegt;gt; Coordinates2D { get; set; } }  

но исправьте свой json до

 {  "features": [  {  "geometry": {  "type": "Point",  "coordinates": [  126.0,  37.0  ]  }  },  {  "geometry": {  "type": "LineString",  "coordinates": [  [  126.0,  37.0  ],  [  126.0,  37.0  ]  ]  }  }  ] }  

Комментарии:

1. Я только что протестировал этот код. И этот код решил то, о чем я думал в течение 5 часов сразу. Для меня этот код близок к искусству. Большое вам спасибо!

2. @Гарри, добро пожаловать!