0

I'm using C# and the NewtonSoft JSON package.

Lets say I've got an object with a property named "MyProp" which itself is a class with two properties, "PropA" and "PropB". It by default it serialises like so:

{ "MyProp": { "PropA": 1 "PropB": 2 } }

I want it to serialise like this:

{ "PropA": 1 "PropB": 2 }

Is there anything I can tag "MyProp" with that will achieve this? Or if I have to write my own JsonConverter, is there a somewhat painless method of doing this?

Clinton
  • 22,361
  • 15
  • 67
  • 163
  • You will need a custom `JsonConverter` to do this. See [Can I specify a path in an attribute to map a property in my class to a child property in my JSON?](https://stackoverflow.com/q/33088462/10263), which is similar but talks about deserialization. Have a look at [Christiano Santos's answer](https://stackoverflow.com/a/37047126/10263) which shows how to implement the `WriteJson` method of the converter so that it works for serialization as well. I have not tested his solution, but it may work for you. – Brian Rogers Dec 03 '18 at 18:00

1 Answers1

1

Don't think you can tag the class with any attributes to get this. A way to achieve what you want is to Serialize to an anonymous type:

var json = JsonConvert.SerializeObject(new {PropA = myProp.PropA, PropB = myProp.PropB});

This will give you what you want for small use cases like this but will become quite tedious for larger classes.

JohanP
  • 5,252
  • 2
  • 24
  • 34