0

I construct a new JObject instance the following way:

return new JObject(
    new JProperty("prop1", prop1),
    new JProperty("prop2", prop2))

I would like, however, to add a key/value pair only if the value is not null. E.g. if prop1 is null, I'd like no a key/value pair 'prop1': null to be added. Can this be done in an elegant way?

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • Did you check 'JsonSerializerSettings'? – hsd Oct 02 '17 at 07:47
  • 1
    @hsd It works fine, thanks. Ideally I'd like to have more control, i.e. with having the ability to do `new JPropertyIfNotNull(...)`, so I still have the ability to add null properties with `new JProperty(...)` but this is fine too. – Rok Povsic Oct 02 '17 at 08:46

1 Answers1

1

You can control it in JsonSerializerSettings. Please take a look on answer How to ignore a property in class if null, using json.net You are creating object dynamically but solution is the same.

hsd
  • 452
  • 5
  • 12