3
votes

This class

class X{
    public string a{get;set}
    public string b{get;set}
}

is serialized like

{..., inst:{a:"value", b:"value"}, ...}

I need object of my class to be serialized like this:

{..., inst: x, ...}

Where x is a+b How can I customize JSON serialization process from my class?

2
Most people finding this Q&A will want to customize the Newtonsoft JSON serialization process, outputting valid JSON that is different than a serialization of all public properties. (OP's output does not appear to be valid JSON, because value x isn't quoted - in that case, can't use this technique.) Simple changes, such as hiding an attribute, can be done using JSON Serialization Attributes. More complex changes require writing custom JsonConverter per class. - ToolmakerSteve

2 Answers

2
votes

Checkout Newton-softs JSON serializer. Its pretty sweet.

Have you tried making a and b private, and then have something like

public string x { get { return a + b; } }
1
votes

Try it like this

class X{
    public string a{private get;set;}
    public string b{private get;set;}
    public string x {get{ return a + b; }}
}

Having a private get removes it from serialization but still allows it to be set. The other option is to do it like this.

class X{
    public string a{set;}
    public string b{set;}
    public string x {get{ return a + b; }}
}