Search code examples
javajsonjsweet

Post Map as JSON using JSweet


I'd like to send a java.util.HashMap converted to JSON from the client to the server.

I'm using JSweet to transpile Java to JavaScript for the client side.

I had a look at XMLHttpRequest and tried to prepare the map for transfer using JSON.stringify(new HashMap<>()) but this resulted in a

TypeError: cyclic object value

on the client side.

These are my relevant dependencies (using 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"

Solution

  • I had to convert the java.util.Map to a jsweet.lang.Object before encoding it as JSON using stringify.

    Here's the code to send a java.util.Map as JSON to the server using JSweet:

    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;
    }
    

    Use it like this:

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