Charlie Hopperson
Charlie Hopperson

Reputation: 415

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:

    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.

Upvotes: 2

Views: 340

Answers (1)

mfanto
mfanto

Reputation: 14428

One thing you can do is take advantage of the DataContract and DataMember attributes to only serialize the data you want.

[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.

What I like about this approach is it let's you keep standard C# property naming conventions, but still output "correctly cased" JSON.

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

will output

{"last_use": 1}

Upvotes: 4

Related Questions