简体   繁体   English

Json.net仅序列化数组的一部分

[英]Json.net serialize only part of array

could anybody tell me how to serialize and deserialize only part of array tools[] without Func delegate where: 谁能告诉我如何在不使用Func委托的情况下仅对部分数组tools[]进行序列化和反序列化:

    public class Tool
    {
        public Tool()
        {
            lastUse = 1;
            running = false;
        }
        public Func<int> action;
        public bool running;
        public int lastUse;
    }
    public static Tool[] tools = new Tool[] { new Tool(), new Tool(), new Tool(),new Tool()};

Thanks in advance for any responses. 预先感谢您的任何回复。

One thing you can do is take advantage of the DataContract and DataMember attributes to only serialize the data you want. 您可以做的一件事是利用DataContractDataMember属性仅序列化所需的数据。

[DataContract]
public class Tool
{
    public Tool()
    {
        lastUse = 1;
        running = false;
    }

    public Func<int> action;

    [DataMember]
    public bool running;

    [DataMember]
    public int lastUse;
}

The result without the attributes: 没有属性的结果:

[{"action":null,"running":false,"lastUse":1},{"action":null,"running":false,"lastUse":1},{"action":null,"running":false,"lastUse":1},{"action":null,"running":false,"lastUse":1}]

With the attributes: 具有以下属性:

[{"running":false,"lastUse":1},{"running":false,"lastUse":1},{"running":false,"lastUse":1},{"running":false,"lastUse":1}]

This works with both Json.NET and DataContractJsonSerialize . 这适用于Json.NETDataContractJsonSerialize

What I like about this approach is it let's you keep standard C# property naming conventions, but still output "correctly cased" JSON. 我喜欢这种方法的地方在于,它让您保持标准的C#属性命名约定,但仍输出“大小写正确”的JSON。

[DataMember(Name="last_use")]
public int LastUse { get; set; }

will output 将输出

{"last_use": 1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM