将Json.net序列化回JSON [英] Serialize Json.net back to JSON

查看:100
本文介绍了将Json.net序列化回JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取 Json.net 对象并将其变回json字符串?我反序列化从rest服务获得的json数据包.然后,我对其进行处理,最后得到一个 JObject s数组.但是然后我需要将其转换回JSON字符串,以将其发送到浏览器.

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 JObjects. But then I need to turn it back into a JSON string to send it to the browser.

如果我有常规对象,那么我可以调用 JsonConvert.Serialize(),但这在 Json.net JObjects 上不起作用

If I had regular objects then I could just call JsonConvert.Serialize() but that doesn't work on Json.net JObjects

推荐答案

如果您有 JObject 或包含 JObjects JArray ,您只需在 JObject (或 JArray )上调用 ToString()即可获取JSON字符串.例如:

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

结果JSON输出:

[
  {
    "foo": "bar",
    "fizz": "buzz"
  },
  {
    "foo": "baz",
    "fizz": "bang"
  }
]

如果您有常规的JObjects数组,则可以将其传递给 JsonConvert.SerializeObject():

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

这将提供与上述完全相同的JSON输出.

This gives exactly the same JSON output as shown above.

JsonConvert.SerializeObject()在单个 JObject 上也可以正常工作:

JsonConvert.SerializeObject() also works fine on a single JObject:

json = JsonConvert.SerializeObject(jo, Formatting.Indented);
Console.WriteLine(json);

输出:

{
  "foo": "bar",
  "fizz": "buzz"
}

编辑

我刚刚在您的问题上注意到了ASP.NET MVC标记.

I just noticed the ASP.NET MVC tag on your question.

如果您在MVC控制器方法中,则可能是在执行以下操作:

If you're inside an MVC controller method then presumably you are doing something like this:

return Json(arrayOfJObjects);

这将不起作用.这是因为MVC使用 JavaScriptSerializer ,它不了解Json.Net JObjects .在这种情况下,您需要做的是使用上面列出的方法之一创建JSON,然后使用 Content 方法从控制器方法中将其返回,如下所示:

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

这篇关于将Json.net序列化回JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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