Rub*_*ink 8 .net json json.net converters jsonconverter
什么时候using Newtonsoft.Json,我可以通过将转换器添加到顶层SerializerSettings或将其提供给转换调用来实现我所需要的- 一切运行良好.
我希望提取一些全局转换器,而不是在实际需要转换的相关位置以声明方式应用.
我知道以下技巧: -
[JsonConverter(typeof(Converters.StringEnumConverter))]直接在类型上键入级别X[JsonConverter(typeof(Converters.StringEnumConverter))]如果成员是类型X[JsonProperty(ItemConverterType=typeof(Converters.StringEnumConverter)]如果成员实际上是一个数组等的项目级别X我遇到的问题是我所使用的一些全局转换器在嵌套类型上运行,例如,如果我有类型的成员Tuple<X[],Nullable<X>>,我无法表达"如果你在处理这个字段时遇到一个X或者任何一个孩子它,转换"语义,而不是得到一个Newtonsoft.Json.JsonSerializationException.
这样的"对于这棵树,还请使用这个转换器吗"机制存在吗?我想避免为我想要转换的任何内容定义顶级类型,然后使用JsonConverterto来标记该类型?
如果我正确理解了您并根据官方文档,您可以直接应用转换器并使用自定义转换器按类型进行过滤:
SomeType someObject = new SomeType();
string json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new MyCustomConverter(typeof(SomeType)));
public class MyCustomConverter : JsonConverter
{
private readonly Type[] _types;
public MyCustomConverter (params Type[] types)
{
_types = types;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();
o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));
o.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return _types.Any(t => t == objectType);
}
}
Run Code Online (Sandbox Code Playgroud)
来源: https: //www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
| 归档时间: |
|
| 查看次数: |
173 次 |
| 最近记录: |