【问题标题】:JSON.NET: How to deserialize from specific json object to a class with a different nameJSON.NET:如何从特定的 json 对象反序列化为具有不同名称的类
【发布时间】:2020-10-23 08:54:27
【问题描述】:

这让我有点发疯,因为我们没有时间要求 API 团队更改他们的响应对象名称。

我们有一个 json 结果如下:

"seqRing": {
      "admStatus": "disabled",
      "status": null,
      "lines": null
    },

而且我需要将 json 反序列化映射到这个类:

public class SequentialRing
    {
        public string admStatus { get; set; }
        public string status { get; set; }
        public List<SeqLinesAttr> SeqLines { get; set; } = new List<SeqLinesAttr>();
    }

如果这是属性名称不同的情况,我可以简单地使用属性顶部的 JsonPropertyAttribute,但我需要为类提供类似的东西。

如果有什么我可以使用的?请。

谢谢!

【问题讨论】:

  • 看起来“seqRing”是一个更大的 JSON 对象中的一个属性。对吗?
  • @devNull erm...是的。那么您在想的是在 SequentialRing 是属性的类中使用 JsonPropertyAttribute 吗?这行得通吗?

标签: c# json json.net


【解决方案1】:

您展示的 JSON 具有“seqRing”作为更大 JSON 对象的属性。为了反序列化,您可以创建一个包装类(或使用现有类),您可以在其中指定该类的 JSON 属性名称:

public class SequentialRingWrapper
{
    [JsonProperty("seqRing")]
    public SequentialRing SequentialRing { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多