【问题标题】:How to skip specific properties when deserializing with newtonsoft json?使用 newtonsoft json 反序列化时如何跳过特定属性?
【发布时间】:2017-03-29 22:14:11
【问题描述】:

我有一个 API,它返回一个包含 6000 个对象的 JSON 数组。每个对象有大约 40 个属性,但我只需要使用大约 20 个。如何忽略某些属性? 这是我当前的代码:

string json = await client.GetStringAsync(string.Format(url));
List<ListModelClass> ListOfStuff = JsonConvert.DeserializeObject<List<ListModelClass>>(JArray.Parse(json).ToString());

public class ListModelClass {
    public string firstProperty { get; set; }
    public string secondProperty { get; set; }
    public string thirdProperty { get; set; }
    ... about 40 more 
}

【问题讨论】:

  • Newtonsoft.Json 将尝试根据名称匹配属性。如果您的类中不存在该属性,则不会添加该属性。
  • 属性上的ScriptIgnore 属性是否有效?
  • @ZacFaragher 我是这么想的,但我想知道它是否仍然进行比较。我正在尝试减少整个操作所需的时间。
  • 如果是这种情况,那么您的源 JSON 响应本身需要修改。
  • @ZacFaragher 那将是最好的情况,但不幸的是这是不可能的。

标签: c# json serialization json.net deserialization


【解决方案1】:

当且仅当模型类中存在同名的属性或者您可以使用[JsonProperty(PropertyName = "your_property_name")]时,JSON 对象中的属性才匹配

因此,您只能在模型类中包含要使用的属性。

【讨论】:

  • 既然我无法更改我的 API,您是否只是建议从 ModelClass 中删除变量?
  • 是的,你可以这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
相关资源
最近更新 更多