不使用杰克逊就无法将哈希图转换为字符串

时间:2019-02-07 15:51:13

标签: java json hashmap jackson jackson-databind

嗨,当我使用下面的代码时,它工作正常:

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

现在,我想从项目中删除所有依赖项,因此我尝试从this link中使用此方法,但是由于键和值对中包含“(双引号),因此无法使用。:

    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(", "))+"}";

所以我尝试直接保存String命令,就像使用下面的代码从杰克逊罐子中使用ObjectMapper类之后那样,但这还是行不通的:

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

使用ObjectMapper类后,Command变量的输出为:

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

我尝试通过jackson-databind github项目,但是在这个级别上,对于我来说太简单了。请让我知道我如何实现这一目标。

1 个答案:

答案 0 :(得分:0)

转义与反斜杠一起使用,因此:

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
}