英文:
Is there a better way to build the below string with escape characters and double quotes in Java?
问题
以下是翻译好的部分:
我有以下包含转义字符的字符串。
{"Employee": "{\"Id\":\"1234\",\"isReady\":true}"}
有一个消息发布服务,需要以相同的方式使用转义字符和双引号发布字符串。目前,我正在使用下面的方法构建上述字符串。
String beginning = "{\"Employee\": \"";
String needToFormat = "{\"Id\":\"1234\",\"isReady\"";
String end = ":true}\"}";
String formatted = needToFormat.replaceAll("\"", "\\\\\"");
String finalOutput = beginning + formatted + end;
有更好的方法吗?由于某种限制,我不能使用Apache commons库。对于使用Java内置字符串方法或Jackson Json构建此字符串的其他方法,我将不胜感激。
英文:
I have the below string with escape characters in it.
{"Employee": "{\"Id\":\"1234\",\"isReady\":true}"}
There is a message publishing service which requires the string to be published in the exact same way with escape characters and double quotes. Currently I'm building the above string in the below shown method.
String beginning = "{\"Employee\": \"";
String needToFormat = "{\"Id\":\"1234\",\"isReady\"";
String end = ":true}\"}";
String formatted = needToFormat.replaceAll("\"", "\\\\\"");
String finalOutput = beginning + formatted + end;
Is there a better way to do this? I cannot use Apache commons library due to a limitation. Would appreciate any feedback on other ways to build this with Java built in string methods or with Jackson Json.
答案1
得分: 2
要正确且安全地执行此操作,首先将具有属性 "Id" 和 "isReady" 的对象序列化为 JSON。然后将该 JSON 字符串用作 "Employee" 字段的值。
使用 Jackson:
private static final ObjectMapper mapper = new ObjectMapper();
public static String employeeToJson(String id, boolean ready) throws IOException {
String innerJson = mapper.writeValueAsString(Map.of(
"Id", id,
"isReady", ready));
return mapper.writeValueAsString(Map.of("Employee", innerJson));
}
英文:
To do this correctly and safely, first serialize the object with properties "Id" and "isReady" as JSON. Then use that JSON string as the value of the "Employee" field.
With Jackson:
private static final ObjectMapper mapper = new ObjectMapper();
public static String employeeToJson(String id, boolean ready) throws IOException {
String innerJson = mapper.writeValueAsString(Map.of(
"Id", id,
"isReady", ready));
return mapper.writeValueAsString(Map.of("Employee", innerJson));
}
答案2
得分: 1
使用 org.json
JSONObject jo = new JSONObject();
jo.put("Employee", "{\"Id\":\"1234\",\"isReady\":true}");
String finalOutput = jo.toString();
英文:
I don't know this may help you. If not, sorry for my ignorance.
Using org.json
JSONObject jo = new JSONObject ();
jo.put("Employee","{\"Id\":\"1234\",\"isReady\":true}");
String finalOutput = jo.toString();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论