【发布时间】:2021-04-13 02:13:25
【问题描述】:
我正在将 json 反序列化为一个类,它似乎可以工作,但我似乎无法弄清楚如何访问结果。我正在实例化类,然后尝试将反序列化的 json 放入其中,但类容器无法触及。我不确定如何使用各个容器。
这是课程
public class geocodes
{
public Boolean outcome { get; set; }
public double xcord { get; set; }
public double ycord { get; set; }
}
class jsonresult
{
public class Rootobject
{
public Spatialreference spatialReference { get; set; }
public Candidate[] candidates { get; set; }
}
public class Spatialreference
{
public int wkid { get; set; }
public int latestWkid { get; set; }
}
public class Candidate
{
public string address { get; set; }
public Location location { get; set; }
public int score { get; set; }
public Attributes attributes { get; set; }
public Extent extent { get; set; }
}
public class Location
{
public float x { get; set; }
public float y { get; set; }
}
public class Attributes
{
}
public class Extent
{
public float xmin { get; set; }
public float ymin { get; set; }
public float xmax { get; set; }
public float ymax { get; set; }
}
}
这是我用来填充类的代码
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
jsonresult results = System.Text.Json.JsonSerializer.Deserialize<jsonresult>(responseString);
...
}
我想通过每个根容器甚至空间引用进行 foreach(因为它通常会返回多个)如果我只是将 json 的那部分拉到一个类中,我什至会很高兴,但我可以不知道怎么做。
这是json:
{
"spatialReference": {
"wkid": 2253,
"latestWkid": 2253
},
"candidates": [
{
"address": "816 Example ST",
"location": {
"x": 13288754.574891519,
"y": 288356.77197193989
},
"score": 100,
"attributes": {
},
"extent": {
"xmin": 13288098.406912517,
"ymin": 287700.60399293725,
"xmax": 13289410.742870521,
"ymax": 289012.93995094253
}
}
]
}
【问题讨论】:
-
请与我们分享一个示例 json。
-
我会在原文中添加评论。
-
删除周围的
jsonresult类并简单地使用:JsonConvert.DeserializeObject<Rootobject>(responseString) -
谢谢彼得!这真的很有帮助。如果您想发表评论作为答案,我会将 i 标记为答案。
-
我在发布任何内容之前检查了它,所以不用担心,它工作得非常好。
标签: c# json serialization