Deserialize Json from a stream using a custom converter

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 -

  • If I need to pass some additional information to the ctor of the object being deserialized, is my approach of a custom converter right?
  • How can I make the deserialization use my custom converter along with a stream ? I cannot serialize the stream to a string; that results in an OutOfMemoryException.
Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow