Post 使用 JSweet 映射为 JSON

Post Map as JSON using JSweet

我想将 java.util.HashMap 转换为 JSON 从客户端发送到服务器。

我正在使用 JSweet 将 Java 转换为 Java 客户端脚本。

我查看了 XMLHttpRequest 并尝试使用 JSON.stringify(new HashMap<>()) 准备传输地图,但这导致

TypeError: cyclic object value

在客户端。

这些是我的相关依赖项(使用Gradle):

// Java to JavaScript transpilation 
compile "org.jsweet:jsweet-transpiler:1.2.0-SNAPSHOT"
compile "org.jsweet.candies:jsweet-core:1.1.1"
// Allows us to use Java features like Optional or Collections in client code
compile "org.jsweet.candies:j4ts:0.2.0-SNAPSHOT"

在使用 stringify.

将其编码为 JSON 之前,我必须将 java.util.Map 转换为 jsweet.lang.Object

这是使用 JSweet 将 java.util.Map 作为 JSON 发送到服务器的代码:

void postJson(Map<String, String> map, String url) {
    XMLHttpRequest request = new XMLHttpRequest();

    // Post asynchronously
    request.open("POST", url, true);
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    // Encode the data as JSON before sending
    String mapAsJson = JSON.stringify(toJsObject(map));
    request.send(mapAsJson);
}

jsweet.lang.Object toJsObject(Map<String, String> map) {
    jsweet.lang.Object jsObject = new jsweet.lang.Object();

    // Put the keys and values from the map into the object
    for (Entry<String, String> keyVal : map.entrySet()) {
        jsObject.$set(keyVal.getKey(), keyVal.getValue());
    }
    return jsObject;
}

这样使用:

Map<String, String> message = new HashMap<>();
message.put("content", "client says hi");
postJson(message, "http://myServer:8080/newMessage");