3

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?

1
  • 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. Commented Oct 1, 2019 at 9:42

2 Answers 2

2

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

2 Comments

Great idea about sum-property, but I deserialize this object from database first so I need these field to be public. So I will use Newton library, unfortunately there is no solutions from the box.
Consider using dedicated classes for your persistence model and viewmodel (or whatever it is you're serializing to Json). I find this is the easiest way to avoid problems like these. If the mapping between models becomes too complex, consider using automapper to manage it.
1

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; }}
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.