user_mda user_mda - 3 months ago 35
Java Question

Converting a hashmap into a JSON string

I want to convert a hashmap into a json string to send over wire. Here is the code

public static void main(String []args)
throws JSONException, JsonParseException, JsonMappingException, IOException {

Map<String,String> varMap = new MyMap<String,String>();
varMap.put("VAR","123");
varMap.put("OTHER_VAR","234");
Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(varMap);

JSONObject json = new JSONObject();
json.put("Variable",jsonString);
System.out.println("JSON " + json);
}


The output is

JSON {"Variable":"{\"VAR\":\"123\",\"OTHER_VAR\":\"234\"}"}


Which I assume does the right thing, but the examples I've found dont include the backslash in the strng. I understand that the backslash escapes the double quotes and hence none of the string replace method work to replace the backslash.

Is there a trick to get the following output?

JSON {"Variable":{"VAR":"123","OTHER_VAR":"234"}}


Can the custom serialization property be used to somehow not add backslashes?

Answer

This should give you the result you want. You're JSON-encoding a JSON-string and its adding those backslashes to escape those characters.

public static void main(String []args) throws JSONException, JsonParseException, JsonMappingException, IOException{

    Map<String, Object> top = new HashMap<String, Object>();

    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("VAR","123");
    vars.put("OTHER_VAR","234");

    top.put("Variable", vars);

    Gson gson = new GsonBuilder().create();
    String jsonString = gson.toJson(top);
    System.out.println("JSON " + json);
}