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
Best Answer
If you have a
JObject
, or aJArray
containingJObjects
, you can simply callToString()
on theJObject
(orJArray
) to get the JSON string. For example:Resulting JSON output:
If you have a regular array of JObjects, you can pass it to
JsonConvert.SerializeObject()
:This gives exactly the same JSON output as shown above.
JsonConvert.SerializeObject()
also works fine on a singleJObject
:Output:
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:
which will not work. This is because MVC uses the
JavaScriptSerializer
, which does not know about Json.NetJObjects
. 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 theContent
method like this: