【问题标题】:json deserialize into class and access results in c#json反序列化为类并在c#中访问结果
【发布时间】: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&lt;Rootobject&gt;(responseString)
  • 谢谢彼得!这真的很有帮助。如果您想发表评论作为答案,我会将 i 标记为答案。
  • 我在发布任何内容之前检查了它,所以不用担心,它工作得非常好。

标签: c# json serialization


【解决方案1】:

问题的根本原因是额外的(不必要的)层:jsonresult。

jsonresult 没有任何属性,这就是 System.Text.Json 无法正确将数据反序列化到其中的原因。换句话说,在JsonSerializer 通过调用其无参数构造函数创建了jsonresult 类的新实例之后,它不能将读取的值分配给它的任何公共属性。


如果您删除 jsonresult 周围类并在 Deserialize 期间使用 RootObject,则在 JsonSerializer 创建 RootObject 实例之后,它可以使用反射(和基于名称的匹配)使用数据填充其属性。

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2017-02-14
    • 1970-01-01
    • 2021-06-02
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多