0

i got a Class Library myCore.dll it includes a class

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. it references myCode.dll and does some interfacing with json via http. but i want to hide Member 'B' of MyClassA if i do serialization in this project. im using Newtonsoft.Json. But i dont want to reference Newtonsoft in myCode.dll to set the [JsonIgnore] Attribute on MyClassA.B.

so how do i create a custom interface in my console-project that inherits from IMyClassA?

1
  • This is typically handled with Converters, but those expect to decorate the target property which in turn requires a Newtonsoft reference. You'd need to look into something like walking the JObject tree yourself and handling the deserialization based on the implemented interfaces. I don't know your project constraints, but you have to ask yourself if that is worth the complexity and almost certain performance degradation. Commented Oct 23, 2020 at 20:32

1 Answer 1

1

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. 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.

To register the converter, instead of using an anotation on your 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:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.