this question has answer here:
- gson handle object or array 3 answers
using gson, trying force json objects have array value 1 element. although construct json way, jsonparser creates new jsonobject in place of array of length 1. majority of json in system have value arrays greater length 1 , parse correctly.
i discovered while attempting utility method brute forcing jsonobject jsonarray. it's not working out expect.
static jsonarray bruteforcejsonarray(jsonobject object, string key) { if(object.get(key).isjsonarray()) { return object.get(key).getasjsonarray(); } else { system.out.println("broken: " + object.tostring()); jsonobject temp = object.get(key).getasjsonobject(); string fixed = "{'" + key + "':[" + temp.tostring() + "]}"; system.out.println("pre-fix: " + fixed); //parsing here reduces array object - hot prevent? temp = new jsonparser().parse(fixed).getasjsonobject(); system.out.println("fixed: " + object.tostring()); return object.get(key).getasjsonarray(); } }
output:
broken: {"token":{"ner":"o","id":1.0,"word":".","characteroffsetend":765.0,"speaker":"per0","pos":".","lemma":".","characteroffsetbegin":764.0}} pre-fix: {'token':[{"ner":"o","id":1.0,"word":".","characteroffsetend":765.0,"speaker":"per0","pos":".","lemma":".","characteroffsetbegin":764.0}]} fixed: {"token":{"ner":"o","id":1.0,"word":".","characteroffsetend":765.0,"speaker":"per0","pos":".","lemma":".","characteroffsetbegin":764.0}}
an example of majority json appear correctly in system:
{"token":[{"speaker":"per0","pos":"in","lemma":"except","characteroffsetbegin":742.0,"ner":"o","id":1.0,"word":"except","characteroffsetend":748.0},{"characteroffsetend":752.0,"speaker":"per0","pos":"in","lemma":"for","characteroffsetbegin":749.0,"ner":"o","id":2.0,"word":"for"},{"id":3.0,"word":"extra","characteroffsetend":758.0,"speaker":"per0","pos":"jj","lemma":"extra","characteroffsetbegin":753.0,"ner":"o"},{"speaker":"per0","pos":"nn","lemma":"meat","characteroffsetbegin":759.0,"ner":"o","id":4.0,"word":"meat","characteroffsetend":763.0},{"characteroffsetend":764.0,"speaker":"per0","pos":".","lemma":".","characteroffsetbegin":763.0,"ner":"o","id":5.0,"word":"."}]}
is there clever way out of problem - way can force objects arrays can process them in stream without try/catch or if/else handling?
static jsonarray bruteforcejsonarray(jsonobject object, string key) { if (object.get(key).isjsonarray()) { return object.get(key).getasjsonarray(); } else { jsonarray oneelementarray = new jsonarray(); oneelementarray.add(new jsonobject()); return oneelementarray; } }
although, shouldn't work jsonobject
/jsonarray
directly. make pojo class data , use gson deserialize json.
Comments
Post a Comment