Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Json using Newtonsoft.json.JsonTextWriter

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");

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?

like image 556
Muhammad Zeeshan Avatar asked May 12 '11 15:05

Muhammad Zeeshan


People also ask

How do I use Newtonsoft JSON?

Use the Newtonsoft. Json; To build and run the app, press F5 or select Debug > Start Debugging. Select the Click Me button to see the contents of the TextBlock object replaced with JSON text.

Is Newtonsoft JSON free?

Json.NET is open source software and is completely free for commercial use.

What is JSON writer?

public interface JsonWriter extends Closeable. Writes a JSON object or array structure to an output source. The class Json contains methods to create writers from output sources ( OutputStream and Writer ). The following example demonstrates how write an empty JSON object: JsonWriter jsonWriter = Json.

What is Newtonsoft JSON formatting indented?

Use Namespace Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting provides formatting options to Format the Json. None − No special formatting is applied. This is the default. Indented − Causes child objects to be indented according to the Newtonsoft.


1 Answers

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.


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

jsonWriter.WriteEndObject();

Then call the StringBuilder's ToString() method:

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

References:

StringWriter Constructor (MSDN) | Reading and Writing JSON (NewtonKing.com)

like image 114
Richard Benson Avatar answered Oct 07 '22 05:10

Richard Benson