【问题标题】:C# JSON deserializer returning list of empty objects [duplicate]C# JSON 反序列化器返回空对象列表 [重复]
【发布时间】:2018-02-03 15:58:14
【问题描述】:

我正在尝试将 json 对象数组转换为 C# 列表,但我无法使其工作。目前,我已经做了这个类:

public class FineModel
{
    public String officer { get; internal set; }
    public String target { get; internal set; }
    public int amount { get; internal set; }
    public String reason { get; internal set; }
    public String date { get; internal set; }

    public FineModel() { }
}

现在,我想要反序列化这个 JSON,它的格式似乎正确:

[  
   {  
      "officer":"Alessia Smith",
      "target":"Scott Turner",
      "amount":1800,
      "reason":"test",
      "date":"9/4/2017 3:32:04 AM"
   }
]

应该发挥魔力的 C# 行是:

List<FineModel> removedFines = JsonConvert.DeserializeObject<List<FineModel>>(json);

它返回一个对象,但是当我尝试打印它的值时,它为 amount 属性返回 0 并为字符串返回空,就像我一样。这里有什么问题?

提前致谢!

【问题讨论】:

  • 你尝试过公共设置器而不是声明构造器吗?

标签: c# json deserialization


【解决方案1】:

从setter中移除内部,

public class RootObject
{
    public string officer { get; set; }
    public string target { get; set; }
    public int amount { get; set; }
    public string reason { get; set; }
    public string date { get; set; }
}

内部设置器将无法工作,因为从另一个 dll 调用

【讨论】:

  • 这个成功了,也谢谢你
  • @Xabi 欢迎,:)
【解决方案2】:

只是为了使答案更完整,从设置器中删除 internal 或将 JsonProperty 属性添加到您的模型。

public class FineModel
{
    [JsonProperty]
    public String officer { get; internal set; }
    [JsonProperty]
    public String target { get; internal set; }
    [JsonProperty]
    public int amount { get; internal set; }
    [JsonProperty]
    public String reason { get; internal set; }
    [JsonProperty]
    public String date { get; internal set; }

    public FineModel() { }
}

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多