使用Json.NET在JSON数组中转义双引号

时间:2015-10-01 15:36:20

标签: c# json.net

我使用Json.NET生成一些我写入webrequest流的JSON。以下是我使用的代码:

dynamic jsonObject = new JObject();
jsonObject.keyName1 = "XXX";
jsonObject.keyName2 = 180539;
jsonObject.keyName3 = new JArray() as dynamic;

dynamic jsonObject2 = new JObject();
jsonObject2.what = "xxxxx";
jsonObject.keyName3.Add(jsonObject2);

jsonObject2 = new JObject();
jsonObject2.what = "yyyyy";
jsonObject2.duration = 30;
jsonObject.keyName3.Add(jsonObject2);

jsonObject2 = new JObject();
jsonObject2.what = "zzzz";
jsonObject2.keyName3.Add(jsonObject2);

jsonObject.keyName4 = "123";

string json = JsonConvert.SerializeObject(jsonObject);

此代码生成以下JSON:

{
  "keyName1": "XXX",
  "keyName2": 180539,
  "keyName3": [
    {"what": "xxxxx"},
    {"what": "yyyyy", "duration":30},
    {"what": "zzzzz"}],
  "keyName4":"123"
}

不幸的是,处理这个JSON的Web服务需要对数组内部的键和值以及数组本身进行转义,如下所示:

{
  "keyName1": "XXX",
  "keyName2": 180539,
  "keyName3": "[
    {\"what\":\"xxxxx\"},
    {\"what\":\"yyyyy\",\"duration\":30},
    {\"what\":\"zzzzz\"}]",
  "keyName4":"123"
}

是否可以使用Json.NET执行此操作?

2 个答案:

答案 0 :(得分:3)

以下是解决方案:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

...

dynamic jsonObject = new JObject();
jsonObject.keyName1 = "XXX";
jsonObject.keyName2 = 180539;
jsonObject.keyName3 = new JArray() as dynamic;

dynamic jsonArrayObject = new JArray() as dynamic;

dynamic jsonObject2 = new JObject();
jsonObject2.what = "xxxxx";
jsonArrayObject.Add(jsonObject2);

jsonObject2 = new JObject();
jsonObject2.what = "yyyyy";
jsonObject2.duration = 30;
jsonArrayObject.Add(jsonObject2);

jsonObject2 = new JObject();
jsonObject2.what = "zzzz";
jsonArrayObject.Add(jsonObject2);

var jsonArrayString = JsonConvert.SerializeObject(jsonArrayObject, Formatting.None);

jsonObject.keyName3 = jsonArrayString;
jsonObject.keyName4 = "123";

string json = JsonConvert.SerializeObject(jsonObject, Formatting.None);

答案 1 :(得分:-1)

在.Net4 + System.Web.HttpUtility.JavaScriptStringEncode