使用GWT中的Javascript覆盖类型创建JSON请求字符串 [英] Create JSON Request string using Javascript Overlay types in GWT
问题描述
我们已在GWT客户端中使用JSO进行JSON解析.现在,我们需要将Java对象转换为JSON字符串.我只是想了解,我们如何实现这一目标? JSO覆盖类型用于JSON解析.还可将其用于创建JSON请求字符串,还是必须通过其他方式?
We have used JSO for our JSON parsing in GWT client side. Now, we need to convert our Java objects to JSON string. I just wanted to understand, how we can achieve this? JSO overlay types was used for JSON parsing. Can it also be used to create a JSON request string or do we have to go by some other means?
推荐答案
在JavaScript中生成JSON对象非常简单.您可以这样做:
Generating a JSON object in JavaScript is pretty simple. You can do it like this:
var obj = { "var1": "hello", "var2": "world" };
这将生成一个带有两个变量(值"hello","world")的JSON对象("var1"和"var2").
可以使用JSON.stringify(jso);
方法将Object转换为String(用于发送).
this will generate a JSON object with two varibles ("var1" and "var2") with their values ("hello", "world").
The Object can be converted into a String (for sending purposes) with the JSON.stringify(jso);
method.
由于无法将所有变量都优化为单个字符串,因此无法从Java代码生成JSON数据(也不会有有用的结果),因此应用此方法将不会获得有用的结果(即使可能).
Generating JSON data from the java code isn't possible (well not with a usefull result) since all varibles are optimzed to single Strings, so applying this method wouldn't hava a usefull result (if even possible).
如果您已经有一个JSO对象(使用诸如safeeval之类的东西生成).您可以在此处编辑变量,如下所示:
If you have already a JSO object (generated with something like safeeval). You can edit your varibles there, like this:
public final native void newValue(String newValue) /*-{
this.ValueName = newValue;
}-*/;
如果您随后希望将该对象作为字符串,则必须在JSO类中定义以下方法:
If you then want the object as string you have to define the following method in your JSO class:
public final native String returnAsString () /*-{
return JSON.stringify(this);
}-*/;
或在您的Java类String s = (new JSONObject(jso)).toString();
中使用它.
or use this in you Java class: String s = (new JSONObject(jso)).toString();
.
这样,您可以编辑原始输入数据并将原始对象发送回服务器.
This way you can edit your original intput data and send the original object back to the server.
BR
这篇关于使用GWT中的Javascript覆盖类型创建JSON请求字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!