VALID JSON - Json.NET WCF 4

Topics: Web Api
Feb 29, 2012 at 3:12 PM

Hi,

 

Just trying to return valid JSON from a WCF 4.0 REST service.

Currently it fails on:

http://jsonlint.com/

when the url supplied is:


http://api.erg.kcl.ac.uk/AirQuality/JsonValid 

Parse error on line 1:
{    "CPU": "Intel
^
Expecting '{', '['

 

This example is the from the source code JsonWriter jsonWriter = new JsonTextWriter. 

ANy idea how to produce valid JSON that will pass the JsonLint test?

 

The interface is:

[WebGet(UriTemplate = "/JsonValid", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]        

Message GetValidJSON();

 

This calls:

 public Message GetValidJSON()       
{           

 return WebOperationContext.Current.CreateTextResponse(JSONResource.jsonValid, "application/json; charset=utf-8", Encoding.UTF8);       

}


 this string called above -   JSONResource.jsonValid

 public static string jsonValid { get; set; }

is filled by the default constructor on the JSONResource class which calls this method below:

public static string CreateValidJSON()     

{       
    // create string objects           
   StringBuilder sb = new StringBuilder();           
   StringWriter sw = new StringWriter(sb);           
   // create a JsonWriter with the stringwriter           
using (JsonWriter jsonWriter = new JsonTextWriter(sw))           
{             
      // set the formattting            
 jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;               
 // start writing             
 jsonWriter.WriteStartObject();             
 jsonWriter.WritePropertyName("CPU");             
 jsonWriter.WriteValue("Intel");             
jsonWriter.WritePropertyName("PSU");             
jsonWriter.WriteValue("500W");             
jsonWriter.WritePropertyName("Drives");            
jsonWriter.WriteStartArray();             
jsonWriter.WriteValue("DVD read/writer");             
jsonWriter.WriteComment("(broken)");            
jsonWriter.WriteValue("500 gigabyte hard drive");             
jsonWriter.WriteValue("200 gigabype hard drive");             
// close current object/array             
jsonWriter.WriteEnd();             
// close object            
jsonWriter.WriteEndObject();                         
}

            // return results            
return sw.ToString();       

}

Feb 29, 2012 at 4:18 PM

This is the preview 6 webapi forums, not WCF O_O

Feb 29, 2012 at 4:20 PM

Also, why arn't you just using the built-in support for JSON?

Return an object... why are you trying to do so much work?