I'm using WebAPI, which relies on JSON .NET for the JSON format. On the C# side I have a DTO that looks like this:
public class DTO1 : IManifestContainer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public HashSet<string> Manifest { get; private set; }
}
public interface IManifestContainer
{
HashSet<string> Manifest { get; }
}
The idea of the IManifestContainer interface is to keep track of the properties that the client is actually sending to the server in the JSON object. For example, if the client sends this JSON:
{"FirstName":"Jojo"}
The Manifest hashset will contain the "FirstName" only. If the client sends:
{"FirstName":"Jojo", "LastName":"Jones"}
The Manifest hashset will contain both "FirstName" and "LastName".
I tried implementing a JsonConverter like this:
public class ManifestJsonConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
JObject jObject = JObject.Load(reader);
// Convert the JObject to a C# object??
// Passing the serializer will call this method again
object retVal = jObject.ToObject(objectType, serializer);
IManifestContainer manifestContainer = (IManifestContainer) retVal;
foreach (var jProperty in jObject.Properties())
{
manifestContainer.Manifest.Add(jProperty.Name);
}
return retVal;
}
public override bool CanConvert(Type objectType)
{
return typeof (IManifestContainer).IsAssignableFrom(objectType);
}
}
I need to load the JObject to obtain all the properties coming from the client, but then I don't know how to create the instance of "objectType" (the C# DTO) from the JObject.