如何在客户端上生成JSON [英] How to genearte JSON on the client

查看:80
本文介绍了如何在客户端上生成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个项目中,我必须将复杂的JSON命令从服务器发送到客户端。是否有效生成JSONObjects(字符串,数字等)将它们转换为字符串,然后通过RequestBuilder发送,或者是否有更有效的方法。



是有效将JSON对象转换为字符串(通过Object上的.toString方法)



代码示例:

  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());

输出:

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

问候,
Stefan

解决方案

如果你想更有效地做到这一点,你只想支持现代浏览器支持 JSON.stringify(),你可以使用 JavaScriptObjects 而不是 JSONObjects 并使用这个本地方法:

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

或者,您可以通过执行以下操作将JSO串联起来:

 字符串json = new JSONObject(jso).toString(); 

JavaScriptObject s更高效,因为它们在最终的编译代码中表示为JS对象,而 JSONObject s表示为模拟的Java对象。第二种解决方案意味着构建JSO时的开销更小,但是当您将其串联化时,相对而言(比第一个更多)。



尽管您的解决方案工作得很好。 / p>

In the project, I have to send complex JSON commands form the server to the client. Is it effective to generate JSONObjects ( Strings, Numbers, etc.) convert them to the string and then send them via RequestBuilder or is there a more effective method.

Is it effective to convert JSON objects to string (via the .toString method on the Object)

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());

Output:

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

Regards, Stefan

解决方案

The solution you have will work.

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

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

Alternatively, you can stringify a JSO by doing:

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

JavaScriptObjects are more efficient because they are represented in the final compiled code as JS objects, while JSONObjects are represented as emulated Java objects. The second solution will mean less overhead while you construct the JSO, but comparatively more (than the first) when you stringify it.

Your solution will work just fine though.

这篇关于如何在客户端上生成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆