I am deserializing a large JSON fragment that I get as a response body from a request to a REST endpoint.
I use the code below
var serializer = new JsonSerializer();
var sr = new StreamReader(responseStream))
var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize<ResultItem>(jsonTextReader);
}
I need some 'metadata' to be injected for each ResultItem when it is constructed. To achieve this I wrote a custom converter as below
public class ResultItemConverter : CustomCreationConverter<ResultItem>
{
private Metadata typeMetadata;
public ResultItemConverter(Metadata typeMetadata)
{
this.typeMetadata = typeMetadata;
}
public override ResultItem Create(Type objectType)
{
return new ResultItem(this.typeMetadata);
}
}
Unfortunately I see no way to pass this converter to the Deserialize method! All examples found use the 'JsonConvert.DeserializeObject' method which allows to specify a converter.
My questions -
You need to customize the serializer itself. For example:
serializer.Converters.Add(new ResultItemConverter());
I don't know whether you have to use a custom converter in this case, but that's how you can do so easily.
See more on this question at Stackoverflow