[英]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: 所以我尝试直接保存String命令,就像使用下面的代码从jackson jars中使用ObjectMapper Class之后那样,但是这也不起作用:
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: 使用ObjectMapper类后,Command变量的输出为:
{"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. 我尝试通过jackson-databind github项目,但是在这个级别上,对于我来说太简单了。 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.