java 使用Jackson将java对象转换为JSON字符串时如何UNESCAPE字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34706849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:13:20  来源:igfitidea点击:

How to UNESCAPE String while converting java object to JSON string using Hymanson

javaHymanson

提问by gauti

I am using Hymanson version 2.4.3 for converting my complex Java object into String object, so below is what I'm getting in output. The output getting like below (Fyi - I just printed some part of output)

我正在使用 Hymanson 版本 2.4.3 将我的复杂 Java 对象转换为 String 对象,所以下面是我在输出中得到的内容。输出如下(Fyi - I just printed some part of output)

"{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";

Here is my code (PaymentTnx is complex Java object)

这是我的代码(PaymentTnx 是复杂的 Java 对象)

ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String lpTransactionJSON = mapper.writeValueAsString(paymentTxn);

I don't wanted to see \ slashesh in my JSON string. What I need to do ? Like below:

我不想在我的 JSON 字符串中看到 \ slashesh。我需要做什么 ?像下面这样:

"{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";

回答by gauti

String test = "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
        System.out.println(StringEscapeUtils.unescapeJava(test));

This might help you.

这可能对你有帮助。

回答by Well Smith

I have not tried Hymanson. I just have similar situation.

我没有试过Hyman逊。我只是有类似的情况。

I used org.apache.commons.text.StringEscapeUtils.unescapeJson but it's not working for malformed JSON format like {\"name\": \"john\"}

我使用了 org.apache.commons.text.StringEscapeUtils.unescapeJson 但它不适用于格式错误的 JSON 格式,例如 {\"name\": \"john\"}

So, I used this class. Perfectly working fine.

所以,我使用了这个类。完美运行。

https://gist.githubusercontent.com/jjfiv/2ac5c081e088779f49aa/raw/8bda15d27c73047621a94359492a5a9433f497b2/JSONUtil.java

https://gist.githubusercontent.com/jjfiv/2ac5c081e088779f49aa/raw/8bda15d27c73047621a94359492a5a9433f497b2/JSONUtil.java

// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.utility.json;

public class JSONUtil {
  public static String escape(String input) {
    StringBuilder output = new StringBuilder();

    for(int i=0; i<input.length(); i++) {
      char ch = input.charAt(i);
      int chx = (int) ch;

      // let's not put any nulls in our strings
      assert(chx != 0);

      if(ch == '\n') {
        output.append("\n");
      } else if(ch == '\t') {
        output.append("\t");
      } else if(ch == '\r') {
        output.append("\r");
      } else if(ch == '\') {
        output.append("\\");
      } else if(ch == '"') {
        output.append("\\"");
      } else if(ch == '\b') {
        output.append("\b");
      } else if(ch == '\f') {
        output.append("\f");
      } else if(chx >= 0x10000) {
        assert false : "Java stores as u16, so it should never give us a character that's bigger than 2 bytes. It literally can't.";
      } else if(chx > 127) {
        output.append(String.format("\u%04x", chx));
      } else {
        output.append(ch);
      }
    }

    return output.toString();
  }

  public static String unescape(String input) {
    StringBuilder builder = new StringBuilder();

    int i = 0;
    while (i < input.length()) {
      char delimiter = input.charAt(i); i++; // consume letter or backslash

      if(delimiter == '\' && i < input.length()) {

        // consume first after backslash
        char ch = input.charAt(i); i++;

        if(ch == '\' || ch == '/' || ch == '"' || ch == '\'') {
          builder.append(ch);
        }
        else if(ch == 'n') builder.append('\n');
        else if(ch == 'r') builder.append('\r');
        else if(ch == 't') builder.append('\t');
        else if(ch == 'b') builder.append('\b');
        else if(ch == 'f') builder.append('\f');
        else if(ch == 'u') {

          StringBuilder hex = new StringBuilder();

          // expect 4 digits
          if (i+4 > input.length()) {
            throw new RuntimeException("Not enough unicode digits! ");
          }
          for (char x : input.substring(i, i + 4).toCharArray()) {
            if(!Character.isLetterOrDigit(x)) {
              throw new RuntimeException("Bad character in unicode escape.");
            }
            hex.append(Character.toLowerCase(x));
          }
          i+=4; // consume those four digits.

          int code = Integer.parseInt(hex.toString(), 16);
          builder.append((char) code);
        } else {
          throw new RuntimeException("Illegal escape sequence: \"+ch);
        }
      } else { // it's not a backslash, or it's the last character.
        builder.append(delimiter);
      }
    }

    return builder.toString();
  }
}

回答by Tassos Bassoukos

This here is not valid JSON:

这在这里不是有效的 JSON:

"{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";

This here is valid JSON, specifically a single string value:

这是有效的 JSON,特别是单个字符串值:

"{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";

Given that you're calling writeValueAsString, this is the correct behaviour. I would suggest writeValue, perhaps?

鉴于您正在调用writeValueAsString,这是正确的行为。我会建议writeValue,也许?