使用 Json.net - ac# 对象的部分自定义序列化
我使用 Newtonsofts 的 Json.Net 将一些对象和数组序列化为 json。 这些对象具有一组通用的属性,但也具有 Meta 属性,它是一个字典
在序列化过程中,我希望将键值对添加到我的 json 对象中,就好像它们位于根级别属性中一样,就像这样...
{
id: 1,
name:'jeff',
food:'spinch',
spoon: 'ýes'
}
不是这样的:
{
id: 1,
name:'jeff',
meta:{
food:'spinch',
spoon: 'ýes'
}
}
我已经挖掘了 JsonSerializerSettings 但似乎无法找到我可以跳入并覆盖的地方???
I ma using Newtonsofts' Json.Net to serialize some and array of objects to json.
The objects have a common set of properties but also have Meta property which is a dictionary
During serialization I want the key value pairs to be added to my json object as if they where root level properties, like this...
{
id: 1,
name:'jeff',
food:'spinch',
spoon: 'ýes'
}
Not like this:
{
id: 1,
name:'jeff',
meta:{
food:'spinch',
spoon: 'ýes'
}
}
I have dug through JsonSerializerSettings but cant seem to spot where I can jump in and override???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过创建自己的
JsonConverter
,然后向要序列化的类添加属性来完成此操作[JsonConverter(typeof(MyConverter))]
示例 -
http:// /www.lostechies.com/blogs/rhouston/archive/2008/02/25/a-custom-converter-for-json-net.aspx
You can do this by creating your own
JsonConverter
and then adding an attribute to the class you want to serialize[JsonConverter(typeof(MyConverter))]
Example here -
http://www.lostechies.com/blogs/rhouston/archive/2008/02/25/a-custom-converter-for-json-net.aspx
如果您的字典是
string
到object
字典,则可以简单地使用[JsonExtensionData]
属性:请参阅 如何使用 Json.Net 将字典序列化为其父对象的一部分。
If your dictionary is a
string
toobject
dictionary could can simply use the[JsonExtensionData]
attribute:See How to serialize a Dictionary as part of its parent object using Json.Net.
您可以使用 .Net DataContractJsonSerializer 。
有关自定义序列化,请参阅:
http://msdn.microsoft .com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx
使用
IDataContractSurrogate
的一个优点(与简单地向类添加属性以进行序列化相比)是,您不需要不必将实际属性和序列化属性混合在同一个类中。另一个优点(与必须对属性包进行自定义序列化相比,ala KeyValuePairConverter )的优点是,您只需向类的属性(实际类型和代理类型)添加属性,并且可以直接针对这些类型编写所有转换/自定义序列化代码。这使您的代码保持更高的水平,并让框架处理确切的传输机制。
You could use the .Net DataContractJsonSerializer.
For custom serialization, see:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx
One advantage of using
IDataContractSurrogate
(compared to simply adding properties to your class for serialization) is that you don't have to mix actual properties and serialization properties together in the same class.Another advantage (compared to having to do custom serialization against a property bag, ala KeyValuePairConverter) is that you only have to add attributes to properties on your classes (the actual type and the surrogate type) and you can write all your conversion/custom serialization code directly against those types. This keeps your code higher level, and lets the framework deal with the exact transport mechanism.