2

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.

1
  • Can you show your data which you want to serialize to this? Commented Dec 27, 2012 at 18:47

1 Answer 1

4

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.