将 json 内容中的 ": " 替换为 ":" 为 string.Replace
string fileName = "file.txt";
string jsonFromSerialization = "{\n\t\"foo\": \"bar\",\n\t\"bar\": \"foo\"\n}"; //JsonConvert.SerializeObject
jsonFromSerialization = jsonFromSerialization.Replace("\": \"", "\":\"");
File.WriteAllText(fileName, jsonFromSerialization);
替换"<any number of whitespaces>:<any number of whitespaces>"
例如。 " : "
通过“:”在带有Regex.Replace的json内容中@
string fileName = "file.txt";
string jsonFromSerialization = "{\n\t\"foo\" : \"bar\",\n\t\"bar\" : \"foo\"\n}"; //JsonConvert.SerializeObject
string pattern = "\"\\s*:\\s*\"";
jsonFromSerialization = Regex.Replace(jsonFromSerialization, pattern, "\":\"");
File.WriteAllText(fileName, jsonFromSerialization);
结果
另一种方法。感谢Jon Skeet 的建议。
在此示例中验证键值中的特殊字符串。
例如。
{"foo": "xyz\": ","bar" : "foo"}
代码
string JsonReplace(string json)
{
string pattern = @"(\s*""\w+"")\s*:\s*";
foreach (Match m in Regex.Matches(json, pattern))
{
json = json.Replace(m.Value, m.Value.Replace(" ", string.Empty));
}
return json;
}
string fileName = "file.txt";
var data = new
{
foo = "xyz\": ",
bar = "foo"
};
string jsonFromSerialization = JsonConvert.SerializeObject(data);
jsonFromSerialization = JsonReplace(jsonFromSerialization);
File.WriteAllText(fileName, jsonFromSerialization);
结果