java - Replace whitespace in JSON keys -
i thinking of best solution replace whitespaces in json keys underscore.
{ "format": "json", "testdata": { "key spaces in it": { "and again": { "child_key1": "financial", "child_key2": null }, ......... .....
i want above converted shown below:
{ "format": "json", "testdata": { "key_with_spaces_in_it": { "and_again": { "child_key1": "financial", "child_key2": null }, ......... .....
any suggestions ?
does java library have predefined function ?
replacing keys
the following code uses google's json parser extract keys, reformat them, , create new json object:
public static void main(string[] args) { string testjson = "{\"testkey\": \"test\", \"test spaces\": { \"child spaces 1\": \"child value 1\", \"child spaces 2\": \"child value 2\" } }"; map oldjsonobject = new gson().fromjson(testjson, map.class); jsonobject newjsonobject = iteratejson(oldjsonobject); gson somegson = new gson(); string outputjson = somegson.tojson(newjsonobject); system.out.println(outputjson); } private static jsonobject iteratejson(map jsondata) { jsonobject newjsonobject = new jsonobject(); set jsonkeys = jsondata.keyset(); iterator<?> keys = jsonkeys.iterator(); while(keys.hasnext()) { string currentkey = (string) keys.next(); string newkey = currentkey.replaceall(" ", "_"); if (jsondata.get(currentkey) instanceof map) { jsonobject currentvalue = iteratejson((map) jsondata.get(currentkey)); newjsonobject.add(currentkey, currentvalue); } else { string currentvalue = (string) jsondata.get(currentkey); newjsonobject.addproperty(newkey, currentvalue); } } return newjsonobject; }
you can read more gson here.
replacing values
depending on how json data set up, might need switch jsonarray jsonobject.
jsonarrays begin , end []
, while jsonobjects begin , end {}
in short, these methods travel on entire array/object , replace spaces underscores. they're recursive, dive child jsonarrays/jsonobjects.
if json data encoded java jsonarray, can following:
public static void removejsonspaces(jsonarray thejson) { (int = 0; while < thejson.length(); i++) { if (thejson.get(i) instanceof jsonarray) { currentjsonarray = thejson.getjsonarray(i); removejsonspaces(currentjsonarray); } else { currententry = thejson.getstring(i); fixedentry = currententry.replace(" ", "_"); currentjsonarray.put(i, fixedentry); } } }
in short, method travel on entire array , replace spaces underscores. it's recursive, dive child jsonarrays.
you can read more jsonarrays here
if data encoded jsonobject, you'd want like:
public static void removejsonspaces(jsonobject thejson) { jobject = new jsonobject(thejson.trim()); iterator<?> keys = jobject.keys(); while(keys.hasnext()) { string key = (string)keys.next(); if (jobject.get(key) instanceof jsonobject) { removejsonspaces(jobject.get(key)) } else { currententry = thejson.getstring(i); fixedentry = currententry.replace(" ", "_"); currentjsonarray.put(i, fixedentry); } } }
you can read more jsonobjects here
Comments
Post a Comment