How to code JSON beautifully in c#

Daniel Lowes
Daniel Lowes used Ask the Experts™
on
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) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://breeding-portal.mystagingwebsite.com/wp-json/acf/v3/listings/726");
xhr.setRequestHeader("authorization", "Basic bG93ZXNhbGV4QGdtYWlsLmNvbTpNYXJ0eW1jZmx5MTIz");
xhr.setRequestHeader("content-type", "application/json");

xhr.send(data);

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("https://breeding-portal.mystagingwebsite.com/wp-json/acf/v3/listings/726");
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

Comment
Watch Question

Do more with

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

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

var person = {};
person.firstName="John";
person.lastName:"Doe";
person.age=50;
person.eyeColor="blue";

var jsonPerson = JSON.stringify(person);

Open in new window


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

Regards,
Rikin
Daniel LowesPHP Web Developer And Computer Tech

Author

Commented:
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
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial