如果它只是一个类中的一个字段,您可以简单地在您的类中添加一个只读属性来处理编码,并对其进行注释,使其在序列化期间取代原始属性:
public class MyModelClass
{
...
[JsonIgnore]
public string SecondField { get; set; }
[JsonProperty("second_field")]
private string UrlEncodedSecondField
{
get { return System.Web.HttpUtility.UrlEncode(SecondField); }
}
...
}
演示小提琴:https://dotnetfiddle.net/MkVBVH
如果您需要跨多个类的多个字段,您可以使用类似于Selectively escape HTML in strings during deserialization 中的解决方案,并进行一些小的更改:
- 创建一个自定义
UrlEncode 属性并让解析器查找具有该属性的属性,而不是缺少 AllowHtml 属性。
- 将
HtmlEncodingValueProvider 更改为UrlEncodingValueProvider 并让它在GetValue 而不是SetValue 中应用编码(这样它就对序列化而不是反序列化进行编码)。
生成的代码如下所示:
public class UrlEncodeAttribute : Attribute { }
public class CustomResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
// Find all string properties that have a [UrlEncode] attribute applied
// and attach an UrlEncodingValueProvider instance to them
foreach (JsonProperty prop in props.Where(p => p.PropertyType == typeof(string)))
{
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null && pi.GetCustomAttribute(typeof(UrlEncodeAttribute), true) != null)
{
prop.ValueProvider = new UrlEncodingValueProvider(pi);
}
}
return props;
}
protected class UrlEncodingValueProvider : IValueProvider
{
PropertyInfo targetProperty;
public UrlEncodingValueProvider(PropertyInfo targetProperty)
{
this.targetProperty = targetProperty;
}
// SetValue gets called by Json.Net during deserialization.
// The value parameter has the original value read from the JSON;
// target is the object on which to set the value.
public void SetValue(object target, object value)
{
targetProperty.SetValue(target, (string)value);
}
// GetValue is called by Json.Net during serialization.
// The target parameter has the object from which to read the string;
// the return value is the string that gets written to the JSON
public object GetValue(object target)
{
string value = (string)targetProperty.GetValue(target);
return System.Web.HttpUtility.UrlEncode(value);
}
}
}
要使用自定义解析器,首先使用新的[UrlEncode] 属性装饰您想要进行 URL 编码的任何属性:
public class MyModelClass
{
[JsonProperty("first_field")]
public string FirstField { get; set; }
[UrlEncode]
[JsonProperty("second_field")]
public string SecondField { get; set; }
...
}
然后,像这样序列化您的模型:
var myObject = new MyModelClass("blablabla", "<>@%#^^@!%");
var settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver(),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(myObject, settings);
演示小提琴:https://dotnetfiddle.net/iOOzFr