Removing a json object from a json file in Java -
i have json file downloaded online:
{ "price": 1, "empty": [ 0, 0, 0, 0, 0 ], "lowvalue": 0, "highvalue": 0 },
and want delete
"empty": [
to
],
i've spent few hours looking @ regex stuff , can't seem figure out how make want do.
edit: annamalai thangaraj's method works until add more file.
{ "price": 1, "empty": [ 0, 0, 0, 0, 0 ], "lowvalue": 0, "highvalue": 0 }, { "price": 500, "empty": [ 5, 0, 3, 6, 9 ], "lowvalue": 4, "highvalue": 2 }
which i'm given error:
exception in thread "main" java.lang.classcastexception: com.google.gson.jsonarray cannot cast com.google.gson.jsonobject
my code exactly:
public static void go() throws ioexception { jsonobject jsonobject = (jsonobject)jsonparser.parse(new filereader(location)); jsonobject.remove("empty"); jsonarray jsonarray = (jsonarray)jsonparser.parse(new filereader(location)); gson gson = new gsonbuilder().setprettyprinting().create(); jsonparser jp = new jsonparser(); jsonelement je = jp.parse(jsonobject.tostring()); string prettyjsonstring = gson.tojson(je); filewriter file = new filewriter(system.getproperties().getproperty("user.home")+"\\output.json"); try { file.write(prettyjsonstring); system.out.println("successfully wrote json object file."); } catch (ioexception e) { e.printstacktrace(); } { file.flush(); file.close(); } }
use following code remove element empty
json
jsonobject jsonobject = (jsonobject) jsonparser.parse(new filereader("file path")); jsonobject .remove("empty");
after removing empty
element using jsonobject.tojsonstring() target json, structure of json this
{ "price": 1, "lowvalue": 0, "highvalue": 0 },