java - Read json token (byte[]) as stream -
lets have json response like:
{ byteprop: [1, 3, 2, ... large byte content] }
i fetch byteprop
stream. have started jacksonstreamingapi , assumed should create parser like:
jsonfactory jfactory = new jsonfactory(); jsonparser jparser = jfactory.createjsonparser( myjsonstream);
bu problem don't see oppurtunity byteprop
as stream, way property use sth (assume on right token)
jparser.getbinaryvalue()
which still fetch byteprop
content memory , situation avoid.
is there way read single json property stream ?
something should work, improve see fit:
bytearrayoutputstream os = new bytearrayoutputstream(); jsonfactory jfactory = new jsonfactory(); jsonparser jparser = jfactory.createjsonparser(new fileinputstream(new file("data/json.json"))); if (jparser.nexttoken() != jsontoken.start_object) { return; } while (jparser.nexttoken() != jsontoken.end_object) { string fieldname = jparser.getcurrentname(); jparser.nexttoken(); if (fieldname.equals("byteprop")) { byte[] bytes = new byte[1024]; int read = 0; while (jparser.nexttoken() != jsontoken.end_array) { if (read >= bytes.length) { os.write(bytes, 0, read); os.flush(); bytes = new byte[1024]; read = 0; } bytes[read++] = jparser.getbytevalue(); } if (read >= 0) { os.write(bytes, 0, read); os.flush(); } } } system.out.println(new string(os.tobytearray()));
replace bytearrayoutputstream
fileoutputstream
, depending on needs.
Comments
Post a Comment