14

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

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

Here is my code (PaymentTnx is a complex Java object)

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

I don't want to see \ slashes in my JSON string. What do I need to do to get a string like below:

"{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";
1
  • Wait. When do you see the slashes? Commented Jan 10, 2016 at 15:02

4 Answers 4

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

This might help you.

Sign up to request clarification or add additional context in comments.

3 Comments

This is actually deprecated. There is an alternative?
Apache has moved this class and function to the different package. org.apache.commons.text.StringEscapeUtils.unescapeJson
And instead of in the commons-lang-x.jar it is now included in the commons-text-x.jar.
7

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

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

So, I used this class. Perfectly working fine.

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

Comments

0

With Jackson do:

toString(paymentTxn);

with

public String toString(Object obj) {
    try (StringWriter w = new StringWriter();) {
        new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
        return w.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Comments

-5

This here is not valid JSON:

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

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

"{\"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?

4 Comments

When we usually use writeValueAsString(Object), then it should give values like "{"FirstName":"John","LastName":cena","salary":7500","skills":["java","python"]}";
Are the double quotes around your result part of the result? Use backticks (`) to visually separate it.
Again, have you tried write in place of writeValueAsString?
Yes, I tried but still same, writeValue has two method writeValue(OutputStram out, Object object) and writeValue (Writter w, Object value)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.