如何在Json字符串中转义Json字符串

时间:2019-05-13 17:58:25

标签: c# .net json

我有一个Windows服务,该服务从数据库加载参数。有一个参数是一个Json字符串,它的字段是另一个Json字符串。

{ 
    "dll_fullname": "ScheduledTask.DialogTechSync.DialogTechSyncTask",
    "dll_para_json": "{"data_length": "5000", "max_parallelism": "4", "pause_time": "20"}"
}

在上面的示例中,dll_para_json是此Json字符串中的Json字符串。

在C#代码中,如果我按如下所示对其进行硬编码,则可以正常工作:

{ \"dll_fullname\": \"ScheduledTask.DialogTechSync.DialogTechSyncTask\",\"dll_para_json\": \"{\"data_length\": \"5000\", \"max_parallelism\": \"4\", \"pause_time\": \"20\"}\" }

但是,如果将其放入数据库中,则在反序列化时会出现异常:

dynamic results = JsonConvert.DeserializeObject<dynamic>(json);

我也尝试将其放在下面

{ \\"dll_fullname\\": \\"ScheduledTask.DialogTechSync.DialogTechSyncTask\\",\\"dll_para_json\\": \\"{\\"data_length\\": \\"5000\\", \\"max_parallelism\\": \\"4\\", \\"pause_time\\": \\"20\\"}\\" }

{ \\\"dll_fullname\\\": \\\"ScheduledTask.DialogTechSync.DialogTechSyncTask\\\",\\\"dll_para_json\\\": \\\"{\\\"data_length\\\": \\\"5000\\\", \\\"max_parallelism\\\": \\\"4\\\", \\\"pause_time\\\": \\\"20\\\"}\\\" }

{ \\\\"dll_fullname\\\\": \\\\"ScheduledTask.DialogTechSync.DialogTechSyncTask\\\\",\\\\"dll_para_json\\\\": \\\\"{\\\\"data_length\\\\": \\\\"5000\\\\", \\\\"max_parallelism\\\\": \\\\"4\\\\", \\\\"pause_time\\\\": \\\\"20\\\\"}\\\\" }

没有工作。总是一样的异常:

Error in parsing job: Newtonsoft.Json.JsonReaderException: After parsing a value an unexpected character was encountered: d. Path 'dll_para_json', line 1, position **.
at Newtonsoft.Json.JsonTextReader.ParsePostValue(Boolean ignoreComments)
at Newtonsoft.Json.JsonTextReader.Read()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJObject(JsonReader reader)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)

有人知道如何解决此问题吗?

谢谢

0 个答案:

没有答案