Postal map as JSON using JSweet

I would like to send java.util.HashMap converted to JSON from client to server.

I use JSweet to translate Java to JavaScript for the client side.

I looked at XMLHttpRequest and tried to prepare the map for migration using JSON.stringify(new HashMap<>()) , but this led to

TypeError: value of a cyclic object

on the client side.

These are my respective 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" 
+5
source share
1 answer

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

Here is the code to send 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 as follows:

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

All Articles