Thursday 23 February 2012

stream a single value as JSON in a whole JSON map

Problem statement 
I have a JSON of following format
{ "a":"b" , "Content" : <Content of file FILEA> , "x" : y" }
and so on.
FILEA is too big that i cant open and load it to main memory. Is there any option where i can stream this json to a webservice without using much of main memory using Java.

Solution
So what i did was , i flicked a java file from gson , added features in it and then used it.
Code - https://github.com/Vineeth-Mohan/Scribblings/blob/master/JsonStreamWriter.java

usage -
    writer = new JsonStreamWriter(new   OutputStreamWriter(urlconnection.getOutputStream()));

    writer.beginObject(); // {
    writer.name("name").value("mkyong"); // "name" : "mkyong"
    writer.name("age").value(29); // "age" : 29
    writer.name("messages"); // "messages" :
    writer.startStreamString();
    writer.streamValue("Stream1"); // "msg 1"
    writer.streamValue("Stream2"); // Keep on writing lines here from a file
    writer.endStreamString();
    writer.endObject(); // }
    writer.close();

No comments:

Post a Comment