JsonReader (C#): Non-cached, forward-only access to JSON data

585 views
Skip to first unread message

Atif Aziz

unread,
Apr 10, 2006, 7:11:46 AM4/10/06
to jay...@googlegroups.com

I have added a JSON text parser, called JsonTextReader, that provides non-cached, forward-only access to JSON data. JsonTextReader [1] can be found in the Jayrock project from version 1.0.7507 onwards. I am mentioning it here in case other libraries may be interested in a similar approach.

 

Background:

 

When I originally started with the Jayrock project, I took off by porting the Java JSONTokener implementation [2] to C# and re-factored it such that it outputs the abstract JSON type system (embodied in IParserOutput) as opposed to specific classes like JSONObject [3] and JSONArray [4]. With JsonTextReader, I've got JSONTokener in the final form I had planned originally. JsonTextReader basically takes JSONTokener and turns its implementation into a yield/continuation approach where it does the heavy-lifting of running a state machine internally instead of requiring it from its users. With a non-caching and forward-only approach, JsonTextReader also allows you to rip through large JSON text without incurring the cost of building an in-memory object graph if all you're interested in is just some pieces of data. Here's an example that build a list of servlet names (see also full example in the test case called "Shred" [5]):

 

JsonReader reader = new JsonTextReader(

  new StringReader(text));

 

ArrayList names = new ArrayList();

 

while (reader.Read())

{

    if (reader.Token == JsonToken.Member &&

        reader.Text == "servlet-name")

        items.Add(reader.ReadString());

}

 

I noticed that JSONObject has been enhanced to be even more liberal in its lexical space, so I have updated the C# implementation similarly. I have also added a Jayrock-JSON solution/project for those who wish to use the JSON-only pieces of Jayrock without importing all the JSON-RPC baggage.

 

[1] http://tinyurl.com/pg4b4

[2] http://www.json.org/javadoc/org/json/JSONTokener.html

[3] http://www.json.org/javadoc/org/json/JSONObject.html

[4] http://www.json.org/javadoc/org/json/JSONArray.html

[5] http://tinyurl.com/mg6zu

 

Reply all
Reply to author
Forward
0 new messages