【问题标题】:Newtonsoft.Json: How can I map specific properties?Newtonsoft.Json:如何映射特定属性?
【发布时间】:2015-05-14 15:28:18
【问题描述】:

想象一下我有这样一门课:

public class Foo
{
    [JSonProperty("a")]
    public int a;

    [JSonProperty("b")]
    public int b;

    public List<Foo> foos;
}

想象一下我有一个像这样的 Json:

{
"a": "0",
"b": "1",
"moreFoos": {
    "total" : "2",
    "foos" : [
        {
            "a" : "2",
            "b" : "3"
        }, 
        {
            "a" : "4",
            "b" : "5"
        }
    ]
}
}

所以,我想做的是用 JsonConvert.DeserializeObject(Foo) 反序列化所有属性,但现在只有“a”和“b”被反序列化。我试图把这样的东西放在 foos 属性上:

[JsonProperty("moreFoos.foos")]
public List<Foo> foos;

但它不起作用,foos 为空。你知道是否有办法以这种方式动态映射属性?当然,我想避免创建一个新类,它的 int 属性名为“total”,另一个名为 foos 作为 Foo 对象列表。

问候, 罗曼。

【问题讨论】:

  • 我只能想到在这里使用动态:JsonConvert.DeserializeObject(Foo) 然后使用一种方法将动态转换为您的对象。否则你可以使用custom deserializer
  • IMO,您应该创建一个直接映射到 json 数据形状的类型。如果您随后更喜欢不同的形状,请为此创建一个新类型并相应地映射。

标签: c# json json.net


【解决方案1】:

一种可能性是在私有嵌套代理类型中序列化列表,如下所示:

public class Foo
{
    struct ListWrapper<T>
    {
        public int total { get { return (foos == null ? 0 : foos.Count); } }

        [JsonProperty(DefaultValueHandling=DefaultValueHandling.Ignore)]
        public List<T> foos { get; set; }

        public ListWrapper(List<T> list) : this()
        {
            this.foos = list;
        }
    }

    [JsonProperty("a")]
    public int a;

    [JsonProperty("b")]
    public int b;

    [JsonIgnore]
    public List<Foo> foos;

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    ListWrapper<Foo>? moreFoos
    {
        get
        {
            return foos == null ? null : (ListWrapper<Foo>?)new ListWrapper<Foo>(foos);
        }
        set
        {
            foos = (value == null ? null : value.Value.foos);
        }
    }
}

(我使用包装器结构而不是类来避免ObjectCreationHandling 设置为Reuse 的问题,其中代理包装器类在获取和填充后永远不会被设置。)

另一种选择是使用JsonConverter 来动态重组您的数据,就像Can I serialize nested properties to my class in one operation with Json.net? 一样,但由于您的类是递归的而进行了调整。

【讨论】:

    猜你喜欢
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    相关资源
    最近更新 更多