使用Newtonsoft.json.JsonTextWriter编写Json [英] Writing Json using Newtonsoft.json.JsonTextWriter

查看:1126
本文介绍了使用Newtonsoft.json.JsonTextWriter编写Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Newtonsoft.json.JsonTextWriter编写json. 这是我的代码:

I am writing a json using Newtonsoft.json.JsonTextWriter. Here is my code:

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);

jsonWriter.Formatting = Formatting.Indented;

jsonWriter.WritePropertyName("Name");
jsonWriter.WriteValue("Allan");

我假设sw具有json格式{"Name":"Allan"}.我如何在某个字符串变量中获取书面文本,以便可以在http请求中使用此json数据?

And i am assuming that sw has the json format {"Name": "Allan"}. How can i get the written text in some string variable so that i can use this json data in my http request?

推荐答案

我的答案现在不相关了,因为问题中的代码示例已被编辑为包括这些行,此处保留以供后代参考,有关更多信息,请参见评论.

My answer is now not relevant, since the code sample in the question has been edited to include these lines, left here for posterity, see comments for more info.

您需要添加以下内容以正确关闭JSON元素:

You will need to add the following to close the JSON elements properly:

jsonWriter.WriteEndObject();

然后调用StringBuilder的ToString()方法:

Then call the StringBuilder's ToString() method:

string strMyString = sb.ToString(); //JSONString

参考文献:

StringWriter构造函数(MSDN) | 读写JSON(NewtonKing.com)

这篇关于使用Newtonsoft.json.JsonTextWriter编写Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆