1

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
Martin Booth
  • 8,485
  • 31
  • 31

2 Answers2

1

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

L.B
  • 114,136
  • 19
  • 178
  • 224
0

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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • I agree with you, and there are still rules around what can/cannot be updated, and what is nullable/not nullable. But for the fields which I allow the consumer to update to null, I still need to be able to detect the difference between the consumer deciding not to update the field (i.e. leave it untouched) vs attempting to update it to a null value. I think L.B. has more or less nailed it. – Martin Booth May 25 '12 at 07:01