Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JsonTextReader twice

Tags:

json

c#

json.net

I am given a stream of json data which contains a field named "type". This type field describes the type of object that needs to be created at runtime. It looks like I am unable to use the JsonTextReader twice and I cannot find away to reset the text reader to the beginning.

using (var streamReader = new StreamReader(stream, Encoding))
using (var jsonTextReader = new JsonTextReader(streamReader))
{
    JToken token = JObject.Load(jsonTextReader);
    var type = (string) token.SelectToken("type");
    var modelType = Type.GetType("Project." + type + ", Project");

    // Fails here
    var obj = serializer.Deserialize(jsonTextReader, modelType);
}

I get this error message. Unexpected token while deserializing object: EndObject.

like image 641
Phil Avatar asked Mar 05 '12 22:03

Phil


3 Answers

You can create a JsonReader from the JToken.

JsonReader reader = token.CreateReader();
like image 153
James Newton-King Avatar answered Oct 11 '22 17:10

James Newton-King


To reset your reader to the begginning, set the Position property of the underlying stream to 0.

streamReader.BaseStream.Position = 0;

Edit: While this will reset your underlying stream, the jsonTextReader is forward-only by definition, which means its line number and position are readonly. For this to work you would have to reset the streamReader position, then feed it into a new JsonTextReader object.

So unfortunately Phil, there is no way to read the JsonTextReader twice since it is forward-only.

Reference: http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonTextReader.htm "Represents a reader that provides fast, non-cached, forward-only access to serialized Json data."

like image 24
Despertar Avatar answered Oct 11 '22 17:10

Despertar


I cover using the JsonTextReader in a memory-efficient format, avoiding the Large Object Heap, etc., in my blog, as per James Newton King's recommendations. You can leverage this and the supplied code to read your JSON multiple times without worrying about the underlying implementation of JsonTextReader.

Comments and feedback always welcome.

like image 34
Paul Mooney Avatar answered Oct 11 '22 16:10

Paul Mooney