How to generate JSON on the client

In the project, I have to send complex JSON commands from the server to the client. Is it efficient to generate JSONObjects (strings, numbers, etc.) Convert them to a string and then send them via RequestBuilder or is there a more efficient method.

Is it efficient to convert JSON objects to string (via the object's .toString method)

Code example:

JSONObject retObject = new JSONObject(); retObject.put("NumberVar", new JSONNumber(1)); retObject.put("StringVar", new JSONString("HelloWorld")); JSONArray arrayVar= new JSONArray(); for (int i = 0; i < 5; i++) { arrayVar.set(i, new JSONString("Array")); } retObject.put("EventParameters", arrayVar); System.out.println(retObject.toString()); 

Exit:

 {"NumberVar":1, "StringVar":"HelloWorld", "EventParameters":["Array","Array","Array","Array","Array"]} 

Regards, Stefan

+8
json gwt
source share
2 answers

The solution you have will work.

If you want to do this more efficiently, and you only want to support modern browsers with JSON.stringify() support, you can work in JavaScriptObjects instead of JSONObjects and use this own method:

 private static native String stringify(JavaScriptObject jso) /*-{ return JSON.stringify(jso); }-*/; 

Alternatively, you can create a JSO by doing the following:

 String json = new JSONObject(jso).toString(); 

JavaScriptObject more efficient because they are represented as JS objects in the final compiled code, and JSONObject represented as emulated Java objects. The second solution would mean less overhead when building the JSO, but relatively more (than the first) when you gated it.

Your solution will work just fine, though.

+9
source share

There are also AutoBeans .

 public interface MyJsonFactory extends AutoBeanFactory { AutoBean<MyJsonObj> myJsonObj(); } public interface MyJsonObj { @PropertyName("NumberVar") int getNumberVar(); @PropertyName("NumberVar") void setNumberVar(int val); @PropertyName("StringVar") String getStringVar(); @PropertyName("StringVar") void setStringVar(String val); @PropertyName("EventParameters") List<String> getEventParameters(); @PropertyName("EventParameters") void setEventParameters(List<String> val); } MyJsonFactory factory = GWT.create(MyJsonFactory.class); AutoBean<MyJsonObj> bean = factory.myJsonObj(); MyJsonObj obj = bean.as(); // bean and obj are 2 distinct view on the exact same data obj.setNumberVar(1); obj.setStringVar("HelloWorld"); List<String> list = new ArrayList<String>(5); for (int i = 0; i < 5; i++) { list.add("Array"); } obj.setEventParameters(list); System.out.println(AutoBeanCodex.encode(bean).getPayload()); 

@PropertyName required since your JSON property names do not align with AutoBean conventions (inspired by Java Beans), where getNumberVar() gets the numberVar property (lowercase n )

+3
source share

All Articles