I have a c# class which looks like
public class Node {
public int Id { get; set; }
/** Properties omitted for sake of brevity **/
public Node ParentNode { get; set; }
}
From a browser, I submitted a JSON object as follows
{"Id":1, "ParentNode":1}
Where the value 1 assigned to the ParentNode property representes a database identifier. So, in order to bind properly to my model, i need to write a custom JSON converter
public class NodeJsonConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
/** Load JSON from stream **/
JObject jObject = JObject.Load(reader);
Node node = new Node();
/** Populate object properties **/
serializer.Populate(jObject.CreateReader(), node);
return node;
}
}
Because i get a "Current JsonReader item is not an object: Integer. Path ParentNode'", how can adapt the ReadJson method in order to bind the ParentNode property or anything else which needs custom conversion ?
UPDATE
I have seen JsonPropertyAttribute whose API documentation states
Instructs the JsonSerializer to always serialize the member with the specified name
However, how can i instruct programatically a JsonSerializer - in my case, in the ReadJson method - to use a given JsonPropertyAttribute ?
http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonPropertyAttribute.htm