java - Parse incoming JSON and remove wrapping boilerplate -
within program i'm calling api returns list of users. result wrapped in boilerplate this.
{ "d": { "result" : [ ... here actual lsit ... ] } }
i want parse result, cannot find easy way remove "d" , "result" incoming json string
i started creating own class staging user entity, because resultset not match users entity
class staginguser { // same props api response per user }
my thought parse useres this
private list<staginguser> parseresult(@requestbody list<staginguser> stagingusers) { return stagingusers; }
however require me rid of boilerplate result
you can use gson library. gson-2.8.0.jar
ignoring "d":
maven:
<dependency> <groupid>com.google.code.gson</groupid> <artifactid>gson</artifactid> <version>2.8.0</version> </dependency>
staginguser:
public class staginguser { private string hi; private string name; private string lastname; public staginguser() { } public string gethi ( ) { return hi; } public void sethi ( string hi ) { this.hi = hi; } public string getname ( ) { return name; } public void setname ( string name ) { this.name = name; } public string getlastname ( ) { return lastname; } public void setlastname ( string lastname ) { this.lastname = lastname; } @override public string tostring ( ) { return "staginguser [hi=" + hi + ", name=" + name + ", lastname=" + lastname + "]"; } }
jsontest:
this getting json string format, parsing ignoring d wrapper, , set attributes stagingusers. printing informational purposes
import com.google.gson.jsonarray; import com.google.gson.jsonelement; import com.google.gson.jsonobject; import com.google.gson.jsonparser; public class jsontest { public static void main ( string [ ] args ) { string jsoninstring = "{ \"d\": { \"result\" : [ \"hello\", \"frank\", \"provost\" ] } }"; system.out.println ( "printing json string" ); system.out.println ( jsoninstring ); system.out.println ( ); jsonparser parser = new jsonparser(); jsonobject jsonobject = parser.parse(jsoninstring).getasjsonobject().get("d").getasjsonobject(); jsonarray jsonarray = jsonobject.get("result").getasjsonarray(); system.out.println ( "printing result elements" ); for( jsonelement property : jsonarray) { system.out.println ( property.getasstring ( )); } system.out.println ( ); staginguser user = new staginguser ( ); user.sethi ( jsonarray.get ( 0 ).getasstring ( ) ); user.setname ( jsonarray.get ( 1 ).getasstring ( ) ); user.setlastname ( jsonarray.get ( 2 ).getasstring ( ) ); system.out.println ( "printing pojo: " ); system.out.println ( user.tostring ( ) ); } }
output:
printing json string
{ "d": { "result" : [ "hello", "frank", "provost" ] } }
printing result elements
hello
frank
provost
printing pojo:
staginguser [hi=hello, name=frank, lastname=provost]
Comments
Post a Comment