I got a data model like that:
public struct Person
{
public string Name;
public Address[] Addresses;
}
public struct Address
{
public string HouseNumber;
public string StreetName;
}
I want to use Newtonsoft JSON (or an alternative) to serialize and deserialize an array of persons to two different data sources/web APIs, both names the properties differently.
For example, source 1 would return something like:
[{"name":"John", "addresses":[{"house":12, "name","Floura St"}]}]
While source 2 is like:
[{"person-name":"John", "addresses":[{"houseNumber":12, "street-name","Floura St"}]}]
Actual data can have more or less fields from different sources.
My idea was to have two different JsonSerializerSettings
with different ContractResolver
or different JsonConverter[]
for the two different sources.
I tried overriding
ResolvePropertyName
ofDefaultContractResolver
but didn't work because there is no way to know which type it is resolving property names for. I need that because some properties has the same name between different types.I've also tried overriding
CreateProperties
inDefaultContractResolver
but didn't figure out how to change the mapping for the property name.Finally I tried writing something like this:
private class DynamicConverter<T> : JsonConverter { public DynamicConverter(Dictionary<string, string> propertiesMap) { } public override bool CanConvert(Type objectType) { return objectType == typeof(T); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { } }
But I am not sure if that is the correct way to go, specially that I will need to write all the read and write code from scratch as I guess. Is there a better way to just override the behaviour I am interested in changing without reinventing the wheel? Also I am not sure what I will do with creating a new instance of Person
and Address
because they are structures and not classes.
NOTE: As you may have already guessed, I don't have much access to change the model structs to make them classes or to tag them with Newtonsoft JSON attributes. In fact my team prefer to leave them untouched and not referencing JSON libraries because the model structs live in a common library that is used for a lot of other stuff not related to JSON serialization.
Also note that this is a simple example to demonstrate my problem, the actual data structure is way more complicated, for example there are tens of structs and nested arrays of more than two levels.