Reputation: 4722
How do I take a Json.net
object and turn it back into a string of json?
I deserialize a json packet that I get from a rest service. Then I process it and end up with an array of JObject
s. But then I need to turn it back into a JSON string to send it to the browser.
If I had regular objects then I could just call JsonConvert.Serialize()
but that doesn't work on Json.net
JObjects
Upvotes: 0
Views: 346
Reputation: 129817
If you have a JObject
, or a JArray
containing JObjects
, you can simply call ToString()
on the JObject
(or JArray
) to get the JSON string. For example:
JObject jo = new JObject();
jo.Add("foo", "bar");
jo.Add("fizz", "buzz");
JObject jo2 = new JObject();
jo2.Add("foo", "baz");
jo2.Add("fizz", "bang");
JArray ja = new JArray();
ja.Add(jo);
ja.Add(jo2);
string json = ja.ToString();
Console.WriteLine(json);
Resulting JSON output:
[
{
"foo": "bar",
"fizz": "buzz"
},
{
"foo": "baz",
"fizz": "bang"
}
]
If you have a regular array of JObjects, you can pass it to JsonConvert.SerializeObject()
:
JObject[] arrayOfJObjects = new JObject[] { jo, jo2 };
json = JsonConvert.SerializeObject(arrayOfJObjects, Formatting.Indented);
Console.WriteLine(json);
This gives exactly the same JSON output as shown above.
JsonConvert.SerializeObject()
also works fine on a single JObject
:
json = JsonConvert.SerializeObject(jo, Formatting.Indented);
Console.WriteLine(json);
Output:
{
"foo": "bar",
"fizz": "buzz"
}
EDIT
I just noticed the ASP.NET MVC tag on your question.
If you're inside an MVC controller method then presumably you are doing something like this:
return Json(arrayOfJObjects);
which will not work. This is because MVC uses the JavaScriptSerializer
, which does not know about Json.Net JObjects
. What you need to do in this case is create your JSON using one of the methods I listed above, then return it from your controller method using the Content
method like this:
string json = JsonConvert.SerializeObject(arrayOfJObjects);
return Content(json, "application/json");
Upvotes: 1