JSONConvert SerializeObject不转义单引号

时间:2019-03-08 21:58:21

标签: c# json serialization

C#,我有一个Automobile类,并且在该类中有一个VehicleTrim字段。 我使用public String calculateExpression(String expression){ double dres = 0.0; String[] split = expression.split("(?=[*/+-])|(?<=[*/+-])"); dres = Double.parseDouble(split[0]); for (int i = 1; i < split.length; i+= 2) { String op = split[i]; double val = Double.parseDouble(split[i+1]); switch (op) { if(case == "+" or case == "*") { case "+": dres = Addition(dres, val); break; case "*": dres = Multiplication(dres, val); break; } else { case "-": dres = Subtraction(dres, val); break; case "/": dres = Division(dres, val); break; } default: break; } } String res = Double.toString(dres); return res; } 来序列化该类,并且它没有转义单引号。 当我尝试通过JsonConvert.SerializeObject函数设置Web中对象的值时,这会引起问题。

示例:

window.localStorage.setItem

所以现在我想通过调用此json对象将其设置为Web的本地存储

public class Automobile
{
    public string vehicleTrim { get; set; }
}

var test = new Automobile()
{
    vehicleTrim = "designer's package"
};

var serialized = JsonConvert.SerializeObject(test, Formatting.None);
// serialized output: {"vehicleTrim":"designer's package"}
// expected output :  {"vehicleTrim":"designer\'s package"}

EvaluateJavascriptAsync尝试读取json var jsSetScript = $"window.localStorage.setItem('automobile', '{serialized}');"; await Control.EvaluateJavascriptAsync(jsSetScript);

时返回此错误

我巧妙地用转义的单引号进行了尝试,这很好。所以问题是如何使serializedobject方法转义单引号?

1 个答案:

答案 0 :(得分:1)

"\'"甚至不是有效的JSON字符串文字。来自JSON spec

JSON string specification

因此'不需要转义,但如果必须转义,则必须显示为"\u0027"。仅列出的8个字符具有特殊的缩写转义语法。 (有关更多详细信息,请参见RFC 8259。)

如果"\u0027"满足您的需求,那么将JsonSerializerSettings.StringEscapeHandling设置为StringEscapeHandling.EscapeHtml应该可以解决问题。来自docs

  

StringEscapeHandling枚举

     

指定编写JSON文本时如何对字符串进行转义。

        
Default           0   Only control characters (e.g. newline) are escaped.
EscapeNonAscii    1   All non-ASCII and control characters (e.g. newline) are escaped.
EscapeHtml        2   HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped.

因此,以下操作成功了:

var settings = new JsonSerializerSettings
{
    StringEscapeHandling = StringEscapeHandling.EscapeHtml,
};
var serialized = JsonConvert.SerializeObject(test, Formatting.None, settings);

Console.WriteLine(serialized);
// Outputs {"vehicleTrim":"designer\u0027s package"}

Assert.IsTrue(!serialized.Contains('\'')); 
// Succeeds

演示小提琴here