简体   繁体   中英

Not able to convert hashmap to String without using jackson

Hi when I had used below code then it was working fine:

Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", downloadPath);
commandParams.put("params", params);
HttpClient httpClient = HttpClientBuilder.create().build();

ObjectMapper objectMapper = new ObjectMapper();
String command = objectMapper.writeValueAsString(commandParams);

Now I want to remove all dependencies from my project so i tried using this approach from this link but it doesn't work as key and value pair have "(double quotes) in it.:

    Map<String, Object> commandParams = new HashMap<>();
    commandParams.put("cmd", "Page.setDownloadBehavior");
    Map<String, String> params = new HashMap<>();
    params.put("behavior", "allow");
    params.put("downloadPath", downloadPath);
    commandParams.put("params", params);
    HttpClient httpClient = HttpClientBuilder.create().build();

    String command ="{"+commandParams.entrySet().stream().map(e -> "\""+e.getKey() + "\"" + ":\"" + String.valueOf(e.getValue()) + "\"").collect(Collectors.joining(", "))+"}";

So i tried saving the String command directly as it would have been after using ObjectMapper Class from jackson jars using below code but this also doesn't work:

    Map<String, Object> commandParams = new HashMap<>();
    commandParams.put("cmd", "Page.setDownloadBehavior");
    Map<String, String> params = new HashMap<>();
    params.put("behavior", "allow");
    params.put("downloadPath", downloadPath);
    commandParams.put("params", params);
    HttpClient httpClient = HttpClientBuilder.create().build();

    String command = "{\"cmd\":\"Page.setDownloadBehavior\",\"params\":{\"downloadPath\":\"C:\\\\Users\\\\I334253\\\\Downloads\\\\Test_Download\",\"behavior\":\"allow\"}}";

The output of Command variable after using ObjectMapper Class was:

{"cmd":"Page.setDownloadBehavior","params":{"downloadPath":"C:\\Users\\I334253\\Downloads\\Test_Download","behavior":"allow"}}

I tried going through the jackson-databind github project but its simply too much for me to understand at this level. Please let me know how i can achieve this.

Escaping works with backslash, so do:

String command = commandParams.entrySet().stream()
    .map(e -> "\"" + escape(e.getKey()) + "\"" + ":\""
        + escape(String.valueOf(e.getValue())) + "\"")
    .collect(Collectors.joining(", ", "{", "}"));


static String escape(String s) {
    return s.replace("\\", "\\\\") // Single backslash
        .replace("\"", "\\\"");    // Double quote
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM