简体   繁体   English

c#如何为序列化指定自定义接口

[英]c# How to specify custom Interface for Serialization

i got a Class Library myCore.dll it includes a class我有一个类库 myCore.dll 它包含一个类

public interface IMyClassA {
    public string A { get; set; }
    public string B { get; set; }
}

public class MyClassA: IMyClassA {
    public string A { get; set; }
    public string B { get; set; }
}

then i got a console project with a selfhosted http service.然后我得到了一个带有自托管 http 服务的控制台项目。 it references myCode.dll and does some interfacing with json via http.它引用 myCode.dll 并通过 http 与 json 进行一些接口。 but i want to hide Member 'B' of MyClassA if i do serialization in this project.但如果我在这个项目中进行序列化,我想隐藏 MyClassA 的成员“B”。 im using Newtonsoft.Json.我正在使用 Newtonsoft.Json。 But i dont want to reference Newtonsoft in myCode.dll to set the [JsonIgnore] Attribute on MyClassA.B.但我不想在 myCode.dll 中引用 Newtonsoft 来设置 MyClassA.B 上的 [JsonIgnore] 属性。

so how do i create a custom interface in my console-project that inherits from IMyClassA?那么如何在从 IMyClassA 继承的控制台项目中创建自定义界面?

You have to write a custom converter.您必须编写一个自定义转换器。

If you use NewtonSoft you will have two methods to override: ReadJson(...) and WriteJson(...), one is for serializing the other for deserializing.如果您使用 NewtonSoft,您将有两种方法可以覆盖:ReadJson(...) 和 WriteJson(...),一种用于序列化,另一种用于反序列化。 That way you can write you own code responsible for serializing and deserializing.这样您就可以编写自己的代码来负责序列化和反序列化。 Having your own code you can just ignore the member 'B' of MyClassA.拥有自己的代码,您可以忽略 MyClassA 的成员“B”。

To register the converter, instead of using an anotation on your DTO注册转换器,而不是在 DTO 上使用注释

[JsonConverter(typeof(MyCustomConvreter))]
public interface IMyClassA {
    public string A { get; set; }
    public string B { get; set; }
}

which would lead to an undesired reference to Newtonsoft, you can do this to register the custom converter:这会导致对 Newtonsoft 的不良引用,您可以这样做来注册自定义转换器:

var jsonSerializer = new JsonSerializer();
jsonSerializer.Converters.Add(new MyCustomConverter());

Check NewtonSoft docs for a custom converter: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm检查 NewtonSoft 文档以获取自定义转换器: https ://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM