Detecting the difference between null property and omitted property in JSON

356 Views Asked by At

I have a RESTful webservice which receives JSON and it deserialises it into a c# class using the DataContractJsonSerializer, though this can be changed.

Its purpose is to update fields on a resource

e.g.:

{
    "firstName" : "Martin"
}

I don't necessarily want to update all the fields, and I was hoping to find a way to detect fields which are and are not unspecified in the JSON.

I can't find a way to do this however because I don't know how to tell the difference between an unspecified field and a field which should be updated to null

e.g: (don't update any fields):

{}

vs: (update the firstName field to null)

{
    "firstName" : null
}

What is the best way to approach this?

2

There are 2 best solutions below

0
On BEST ANSWER

I think you can use a field initialized with some random string

public class TestClass
{
    public string firstName = "some string";
}

If you deserialize using {"firstName" : null}, firstName will be null. if you deserialize using {} firstName won't change (some string)

PS: Don't use DataContract or DataMember attributes if you are using DataContractJsonSerializer

1
On

I'm not sure who is using your webservice, but this sounds like something that you should decide and then tell your consumers how it works (rather than relying on the consumer to do it right). I don't think it would be wise to say all fields either can or can not be set to null, so each instance would be handled differently.