How to code JSON beautifully in c#

Daniel Lowes
Daniel Lowes used Ask the Experts™
I want the code to look beautiful but have Bugphobia .
Let me explain my fear:I am afraid to add wired spaces to break my code I want a convention to help me make it look nice without breaking it.
this is  post request of the real code where I changed the secret fields to pseudo fields .
look how beautiful the JavaScript looks like but it's deceiving as i am going to transform all VALUES into variables later (json does not like variables).
Here is the javascript (which looks good ):

var data = JSON.stringify({
  "fields": {
    "horse_colour": "brown",
    "birth_date": "2011",
    "sire_name": "sire name",
    "dam_name": "dam name"

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
});"POST", "");
xhr.setRequestHeader("authorization", "Basic bG93ZXNhbGV4QGdtYWlsLmNvbTpNYXJ0eW1jZmx5MTIz");
xhr.setRequestHeader("content-type", "application/json");


Open in new window

This is a working C# code using RESTSHARP (which I am looking for a pretty way to organise it READY FOR VARIABLES.(the values).

var client = new RestClient("");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic bG93ZXNhbGV4QGdtYWlsLmNvbTpNYXJ0eW1jZmx5MTIz");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "\t{\n  \"fields\": {\n\t\t\"horse_colour\":\"brown\",\n\t\t\"birth_date\":\"2011\",\n\t\t\"sire_name\":\"sire name\",\n\t\t\"dam_name\":\"dam name\"\n  }\n}\n", ParameterType.RequestBody);
IRestResponse response = client.Execute(request); 

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Microsoft Dynamics CRM Consultant

Why don't you first create a JS object and then turn it to JSON?

var person = {};

var jsonPerson = JSON.stringify(person);

Open in new window

You will be able to use variables as well there!!

Daniel LowesPHP Web Developer And Computer Tech


Thank You very much this solved the code.
Now it's easy to add variables an expand the API requests.

Do more with

Expert Office

Start 7-Day Free Trial