I received the Json file using API in c#.
While serializing the data, there was a problem with the arry.
{
"features":[
{
"geometry":{
"type":"Point",
"coordinates":[
126.0,
37.0
]
},
},
{
"geometry":{
"type":"LineString",
"coordinates":[
[
126.0,
37.0
],
[
126.0,
37.0
]
]
},
}
]
}
This is part of the json file. And the "coordinates" array is repeated, but one is one dimensional and the other is two dimensional. I don't know how to declare this. This is my code. How should I declare the geometry class?
public class JsonClass
{
public string type { get; set; }
public List<features> 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...
}
Please understand that I used a translator because I couldn't speak English. Thank you!
CodePudding user response:
Try this it was tested in VS 2022
var data = JsonConvert.DeserializeObject<Data>(json);
classes
public partial class Data
{
[JsonProperty("features")]
public List<Feature> 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 List<object> _coordinates
{
set
{
if (value != null && value.Count > 0)
if (double.TryParse(value[0].ToString(), out _))
{
Coordinates1D = value.Select(x => Convert.ToDouble(x)).ToList();
}
else
Coordinates2D = value.Select(x => ((JArray)x).ToObject<List<double>>()).ToList();
}
}
public List<double> Coordinates1D { get; set; }
public List<List<double>> Coordinates2D { get; set; }
}
but fix your json before
{
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
126.0,
37.0
]
}
},
{
"geometry": {
"type": "LineString",
"coordinates": [
[
126.0,
37.0
],
[
126.0,
37.0
]
]
}
}
]
}