JSON 反序列化为构造的受保护的 setter 数组 [英] JSON deserialize to constructed protected setter array

查看:27
本文介绍了JSON 反序列化为构造的受保护的 setter 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Newtonsoft JSON 来序列化/反序列化我的对象.其中之一包含一个带有受保护 setter 的数组,因为构造函数自己构建数组并且只操作成员.

I use Newtonsoft JSON to serialize/deserialize my objects. One of those contains an array with a protected setter because the constructor build the array itself and only the members are manipulated.

这可以毫无问题地序列化,但是当涉及到反序列化时,该属性将被忽略,因为它不是公共的.我尝试了一个自定义转换器,也没有调用它,因为它不是公开的.

This can be serialized without problem but when it comes to deserialization the property it is ignored because it is not public. I tried a custom converter with it is also not called because it is not public.

这是一个最小化的例子:

This is a minimized example:

public static class TestCoordsDeserialization
{
    private class Coords
    {
        public Double X { get; set; }
        public Double Y { get; set; }
        public Double Z { get; set; }
        public Double A { get; set; }
    }

    private class Engine
    {
        public string Text { get; set; }
        public int Id { get; set; }
        public Coords[] Outs { get; protected set; }

        public Engine()
        {
            this.Outs = new Coords[3];
            for (int i = 0; i < this.Outs.Length; i++)
            {
                this.Outs[i] = new Coords();
            }
        }
    }

    public static void Test()
    {
        Engine e = new Engine();
        e.Id = 42;
        e.Text = "MyText";
        e.Outs[0] = new Coords() { A = 0, X = 10, Y = 11, Z = 0 };
        e.Outs[1] = new Coords() { A = 0, X = 20, Y = 22, Z = 0 };
        e.Outs[2] = new Coords() { A = 0, X = 30, Y = 33, Z = 0 };
        string json = JsonConvert.SerializeObject(e);
        Console.WriteLine(json); //{"Text":"MyText","Id":42,"Positions":{"Test":9,"Outs":[{"X":10.0,"Y":11.0,"Z":0.0,"A":0.0},{"X":20.0,"Y":22.0,"Z":0.0,"A":0.0},{"X":30.0,"Y":33.0,"Z":0.0,"A":0.0}]}}
        Engine r = JsonConvert.DeserializeObject<Engine>(json);
        double value = r.Outs[1].X; // should be '20.0'
        Console.WriteLine(value);
        Debugger.Break();
    }
}

我怎样才能使 value 成为 20.0?

How can I make value to be 20.0?

推荐答案

[JsonProperty] 属性标记 Outs :

    private class Engine
    {
        public string Text { get; set; }
        public int Id { get; set; }
        [JsonProperty]  // Causes the protected setter to be called on deserialization.
        public Coords[] Outs { get; protected set; }

        public Engine()
        {
            this.Outs = new Coords[3];
            for (int i = 0; i < this.Outs.Length; i++)
            {
                this.Outs[i] = new Coords();
            }
        }
    }

这篇关于JSON 反序列化为构造的受保护的 setter 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆