Search code examples
c#jsonjson.netnancydouble-quotes

JProperty does not generate double quotes for value


I'm trying to create a JSON response that is not based on any class or object. It is very dynamic in nature. Hence I've started to use JObject from Newtonsoft.Json.Linq. While it generates the right constructs, it does not encapsulate the value with double quotes. How can I enforce these double quotes around the values?

Here is a small piece of code I used for testing:

var job = new JObject();
job.Add(new JProperty("name", "filip"));
string nm = "Rob";
job.Add(new JProperty("name2", nm));
job.Add(new JProperty("name4", new JValue("Samantha")));

Results in:

{"name":filip,"name2":Rob,"name4":Samantha}

What I would expect:

{"name":"filip","name2":"Rob","name4":"Samantha"}

Here is a complete example:

public class DynJSonService : NancyModule
{
   public DynJSonService()
   {
      Get["/dynjson"] = _ =>
      {
         var job = new JObject();
         job.Add(new JProperty("name", "filip"));
         string nm = "Rob";
         job.Add(new JProperty("name2", nm));
         job.Add(new JProperty("name4", new JValue("Samantha")));
         return job;
      };
   }
}

Which results in following response as given through the browser when surfing to the url: localhost:4439/FilipsApps/dynjson

{"name":filip,"name2":Rob,"name4":Samantha}

Solution

  • Nancy uses the SimpleJson serializer internally by default, which does not know how to handle JObject and JProperty properly. If you want to use those, you should configure Nancy to use the Json.Net (a.k.a. Newtonsoft.Json) serializer instead. There is a Nancy.Serialization.JsonNet NuGet package for that. After you install that package, it should work correctly. If you need to customize the settings for the Json.Net serializer, there are instructions in the readme.md for that package.