user1149942 user1149942 - 14 days ago 5x
JSON Question

How to deserialize multiple objects from a json stream?

Ok, I have asked questions about something like this before, but this is a different subject, so i feel i should make a new topic about it. I'm sorry if this is something i should not have done...


I'm currently reading a twitterfeed and trying to convert it to lose (status) objects. The code i have now is as follows but fails:

webRequest = (HttpWebRequest)WebRequest.Create(stream_url);
webRequest.Credentials = new NetworkCredential(username, password);
webRequest.Timeout = -1;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Encoding encode = Encoding.GetEncoding("utf-8");
responseStream = new StreamReader(webResponse.GetResponseStream(), encode);
int i = 0;

//Read the stream.
while (_running)
jsonText = responseStream.ReadLine();

byte[] sd = Encoding.Default.GetBytes(jsonText);
stream.Write(sd, i, i + sd.Length);

status s = json.ReadObject(stream) as status;
if (s != null)
//write s to a file/collection or w/e
i = 0;



The idea is: Copy the stream into another stream. and keep trying to read it untill an status object is discovered.
This was ment to prevent the stream for being to little, so it had chance to grow. Ofcourse the stream does not always start at the start of an object, or can be corrupt.

Now i did find the method
, and i think i should use it.
Though i have no experience with streams and i can never find a good example of how to use this.

Is there anyone who can explain to me how to read multiple objects from the stream so i can write them into a list or w/e. I really can't find any good examples on the internets..

Thank you very much for trying!!!


I used Json.Net library and this extension class that makes use of DynamicObject to parse streaming json objects

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("");
webRequest.Credentials = new NetworkCredential("...", "......");
webRequest.Timeout = -1;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Encoding encode = Encoding.GetEncoding("utf-8");
StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());

string line;
while (true)
    line = responseStream.ReadLine();
    dynamic obj = JsonUtils.JsonObject.GetDynamicJsonObject(line);
        Console.WriteLine(obj.user.screen_name + " => " + obj.text);