您可以像这样创建自定义 JsonConverter:
public class EscapeQuoteConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString().Replace("'", "\\'"));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = JToken.Load(reader).Value<string>();
return value.Replace("\\'", "'");
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
}
要仅将其用于 Name 属性,请按属性指定它:
public class Person
{
[JsonConverter(typeof(EscapeQuoteConverter))]
public string Name { get; set; }
}
要将 Converter 应用于所有字符串,请使用:
JsonConvert.SerializeObject(person, Formatting.Indented, new EscapeQuoteConverter());