Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

c# - 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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...