-2

I just have a quick question. I have this JSON string in C#, and I'm wondering if it's correct.

 var json_data1 = "{\"serverName\": \"" + ServerStats.serverName +
               "\",\"cpuLoad\":\" " + ServerStats.cpuLoad +
               "\",\"memLoad\":\" " + ServerStats.memoryLoad +
               "\",\"drive0\":\" " + ServerStats.drive0 +
               "\",\"drive1\":\" " + ServerStats.drive1 +
               "\",\"drive2\":\" " + ServerStats.drive2 +
               "\",\"drive3\":\" " + ServerStats.drive3 +
               "\",\"drive4\":\" " + ServerStats.drive4 +
               "\",\"service0\":\" " + ServerStats.testService0 +
               "\",\"service1\":\" " + ServerStats.testService1 +
               "\",\"service2\":\" " + ServerStats.testService2 +
               "\",\"lastBoot\":\" " + ServerStats.lastBoot + "\"}"; 

Is there anything wrong syntax wise with my JSON string? The reason I'm asking is that the JSON string posts to my API if I take out ",lastBoot:" + ServerStats.lastBoot, but when that line is added into the JSON string, it does not work. Any ideas? Thank you for your help.

EDIT: I updated my JSON string above, will this one work?


10
  • 3
    Yes, you need quotes around everything. You'd be better off using a serialiser, like newtonsoft, to do this work for you rather than manually constructing strings. For validating things, get the contents of json_data1, and stick it in jsonlint.com Commented Feb 5, 2016 at 10:25
  • 1
    FYI, use a StringBuilder Commented Feb 5, 2016 at 10:25
  • Is it a possibility for you to use a Json parser like Json.Net: newtonsoft.com/json ? Commented Feb 5, 2016 at 10:28
  • If you produce your Json you can validate it using JsonLint Commented Feb 5, 2016 at 10:31
  • 1
    "it does not work" -> in what way? Commented Feb 5, 2016 at 10:31

1 Answer 1

0

If your intent on building this your self and not using a parser then this should do it:

Stringbuilder sb = new StringBuilder();
sb.Append("{");
sb.AppendFormat("serverName:'{0}',", ServerStats.serverName);
...etc
sb.Append("}");
var json_data1 = sb.ToString();

your json should be in the format

{serverName:'myserverName', cpuLoad:'myCpuLoad',....}

You can validate you Json using JsonLint

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.