在Java中构建具有转义字符和双引号的以下字符串是否有更好的方法?

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年7月22日 12:35:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63026955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定