4

java.util.HashMapJSONに変換したものをクライアントからサーバーに送信したいと思います。

私はJSweetを使用して、クライアント側で Java を JavaScript にトランスパイルしています。

を見て、XMLHttpRequest転送用のマップを準備しようとしましJSON.stringify(new HashMap<>())たが、これにより、

TypeError: 循環オブジェクト値

クライアント側で。

これらは私の関連する依存関係です(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"
4

1 に答える 1

4

を使用して JSON としてエンコードjava.util.Mapする前に、 をに変換する必要がありました。jsweet.lang.Objectstringify

java.util.MapJSweet を使用して 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");
于 2016-07-10T09:39:21.423 に答える