Json.NET 中仅一个属性的自定义序列化程序 [英] custom serializer for just one property in Json.NET

查看:23
本文介绍了Json.NET 中仅一个属性的自定义序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新发现问题 -- 继承自错误的类,需要是 JsonConverter.

UPDATE Found the issue -- was inheriting from wrong class, needed to be JsonConverter.

我有一个具有 System.Data.Entity.Spatial.DbGeography 类型的 Location 属性的类.默认的 Json.NET 序列化程序会输出这样的 JSON 文本:

I have a class that has a Location property of type System.Data.Entity.Spatial.DbGeography. The default Json.NET serializer puts out JSON text like this:

  ...
  "PlaceType": 0,
  "Location": {
    "Geography": {
      "CoordinateSystemId": 4326,
      "WellKnownText": "POINT (-88.00000 44.00000)"
    }
  },
  "AddedDT": null,
  ...

我希望它显示这样的文本:

I want it to put out text like this:

  ...
  "PlaceType": 0,
  "Location": [-88.00000,44.00000],
  "AddedDT": null,
  ...

...所以在我看来我应该做的是覆盖当前在 DbGeography 类型上使用的任何转换器.

...so it seems to me what I should do would be to override whatever converter is currently being used on the DbGeography type.

到目前为止,我看到的使用 CustomCreationConverters 和 ContractResolvers 的示例似乎解决了如何为正在序列化的主类替换序列化程序,而不是为仅是该类的属性的类型.涉及注释被覆盖的类的示例对我不起作用,因为我没有在我的代码中定义 DbGeography 并且它实际上是一个密封类,因为它没有构造函数并且只能由 internal 工厂方法.

The examples I've seen so far that use CustomCreationConverters and ContractResolvers seem to address how you'd replace the serializer for the main class being serialized, not for a type that's only a property of that class. The examples that involve annotating the class that's being overridden don't work for me because I don't define DbGeography in my code and it's effectively a sealed class because it has no constructor and can only be instantiated by internal factory methods.

有没有办法将 JsonConverter 流利地应用于类型?如果是这样,转换器会是什么样子?我只是覆盖 WriteJson() 方法吗?

Is there a way to apply a JsonConverter to a type fluently? If so, what would the converter look like? Do I just override the WriteJson() method?

推荐答案

原来我只需要从 JsonConverter 继承而不是从 CustomCreationConverter 继承,而我试图改变的其他一切一直都没有问题.

Turns out I just needed to inherit from JsonConverter instead of CustomCreationConverter, and everything else I was trying to change was OK all along.

我仍然不确定是否有一种方法可以流畅地应用 JsonConverter,但是还有另一种方法可以应用 JsonConverter,而无需在域/核心项目中引用 Json.NET 或使用对外围设备的引用来标记域类图书馆:

I'm still not sure if there's a way to apply the JsonConverter fluently, but there is another way to apply the JsonConverter without referencing Json.NET in your domain/core project or marking up your domain classes with references to a peripheral library:

var jsonSerializer = new JsonSerializer();
jsonSerializer.Converters.Add(new DbGeographyConverter());
jsonSerializer.Serialize(jsonWriter, place);

这篇关于Json.NET 中仅一个属性的自定义序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆