I would like to achieve something actually quite simple, but I keep running into walls. I have a class that should give access to a REST-API. Such an ApiClient
should be created on basis of a certain class of my program via constructor. So far, so simple.
Now my first idea was to embed the corresponding data models for the JSON serialization as a private class
inside this outer class. But then it came to my mind that Newtonsoft JSON cannot see private
members. So I thought I would make the classes public
and somehow hide the constructors of these data classes to the outside so that they are only visible from the class ApiClient. But in C# the access modifier friend
, known from VB.net, is missing. But I don't want to set all data classes public
either, because they are basically irrelevant for the rest of the program.
Is there a way to implement this somehow so that it doesn't get too complicated? I have already seen approaches with a private class and a public interface. But I don't think that's very nice either. I also saw an approach using data annotation to make the properties visible to Newtonsoft JSON anyways, but that didn't look too attractive to me either.
To say it in short: I want to transfer data to a REST-API and encapsulate the whole thing in a class. I want to use a class for the data that has to be transferred. But if possible this class should only be visible for the ApiClient class and the serializer.
Is there a best-practice solution for this rather common task?
public class ApiClient {
private ApiClientData _serializableData;
// This class should only be visible to the ApiClient class and the serializer
private class ApiClientData {
public string Data1 {get; private set;}
public int Data2 {get; private set;}
public ApiClientData(SomeOtherDataModel input) {
Data1 = input.SomeVal;
Data2 = input.OtherVal;
}
}
public ApiClient(SomeOtherDataModel baseData) {
_serializableData = new ApiClientData(baseData);
}
public void CallService() {
// Newtonsoft JSON
string jsonString = JsonConvert.SerializeObject(_serializableData);
CallBlackBoxFunctionToCommunicateWithTheRestServer(jsonString);
}
}
public void main() {
SomeOtherDataModel data = GetDataFromSql();
ApiClient client = new ApiClient(data);
client.CallService();
}