0

I am working on implementing an API client in C#. The API I am working on is Close.IO.

They allow updating single fields on an object, ex) updating lead.description

https://developer.close.io/#leads-update-an-existing-lead

Request Body

{
    "description": "Best show ever canceled.  Sad."
}

My question, how would I create a new Lead object in c#, update the "description" property and then only send the updated description property as part of the request body?

public class Lead{
    public int id {get;set;}
    public string description {get;set;}
    public string notes {get;set;}
}

var lead = new Lead(){
    id = 1,
    description = "Best show ever canceled.  Sad."
}
var body = JsonConvert.SerializeObject(lead);
client.Update<Lead>(body);

In the example above, the lead with id 1 would get updated, and the description would get set, and the "notes" property would get cleared out.

Request Body

{
    "id":1,
    "description": "Best show ever canceled.  Sad.",
    "notes" : ""
}

I would only want the "description" field to get updated, and the notes field to go untouched. I'm looking for a clean way to use my typed object and serialize that into the request body and only update dirty properties.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
TWilly
  • 4,863
  • 3
  • 43
  • 73
  • 1
    I guess the big question is, how are you serialising that object? It seems strange that a `null` property should get serialised to an empty string. Then again, I have a similar problem myself with xml, but with deserialising - wcf deserialises null, empty and absent all as null. – oerkelens Aug 16 '17 at 21:10
  • I'm using Json.Net for serialization, I added in additional code to my example to show this – TWilly Aug 16 '17 at 21:12
  • Strange, 5 years ago [someone had the exact opposite problem](https://stackoverflow.com/questions/8833961/serializing-null-in-json-net). Would something have changed, or are we missing a ctor on `Lead` that sets `notes` to a default value? – oerkelens Aug 16 '17 at 21:15

1 Answers1

0

This is built into Json.Net with the following settings..

var data = new { x = 1};
var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var text = JsonConvert.SerializeObject(data, Formatting.Indented, settings);
TWilly
  • 4,863
  • 3
  • 43
  • 73