Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask gson to avoid escaping json in a json response?

Tags:

java

json

gson

I have a response object like this:

public class TestResponse {

    private final String response;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;

    // .. constructors and getters here
}

I am serializing above class using Gson library as shown below:

Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
System.out.println(gson.toJson(testResponseOutput));

And the response I am getting back is shown below:

{
  "response": "{\"hello\":0,\"world\":\"0\"}",
  "error": "OK",
  "status": "SUCCESS"
}

As you can see, my json string in "response" field is getting escaped. Is there any way I can ask gson not to do that and instead return a full response like this:

{
  "response": {"hello":0,"world":"0"},
  "error": "OK",
  "status": "SUCCESS"
}

And also - Is there any problem if I do it above way?

NOTE: My "response" string will always be JSON string or it will be null so only these two values will be there in my "response" string. In "response" field, I can have any json string since this library is calling a rest service which can return back any json string so I am storing that in a string "response" field.

like image 900
john Avatar asked Dec 08 '15 22:12

john


People also ask

How do I remove an escape character from a JSON string in Java?

replaceAll("\\","");

Should JSON be escaped?

JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020).

What is escaped JSON?

Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing.

Does GSON ignore transient fields?

Gson serializer will ignore every field declared as transient: String jsonString = new Gson().

What is Gson in Java?

Gson (by Google) is a Java library that can be used to convert a Java object into JSON string. Also, it can used to convert the JSON string into equivalent java object. There are some other java libraries also capable of doing this conversion, but Gson stands among very few which does not require any pre-annotated java classes...

What does for JSON escape from JSON?

FOR JSON will escape any text unless if it is generated as JSON result by some JSON function/query. In your example, FOR JSON cannot know do you really want raw JSON or you are just sending some free text that looks like JSON. Properly defined JSON is generated with FOR JSON (unless if it has WITHOUT_ARRAY_WRAPPER option) or JSON_QUERY.

What can you do with Gson?

In this gson tutorial, I am giving few examples of very common tasks you can perform with Gson. Table of Contents 1. Prerequisites and dependency 2. Create Gson object 3. Convert Java objects to JSON format 4. Convert JSON to Java Objects 5. Writing an Instance Creator 6. Custom Serialization and De-serialization 7.

What is @expose annotation in Gson?

@Expose marks certain fields of the objects to be excluded, by default, for consideration for serialization and deserialization to JSON. It means that Gson will exclude all fields in a class that are not marked with @Expose annotation.


1 Answers

If your response field can be arbitrary JSON, then you need to:

  1. Define it as an arbitrary JSON field (leveraging the JSON type system already built into GSON by defining it as the root of the JSON hierarchy - JsonElement)

    public class TestResponse {
        private final JsonElement response;
    }
    
  2. Convert the String field to an appropriate JSON object representation. For this, you can use GSON's JsonParser class:

    final JsonParser parser = new JsonParser();
    
    String responseJson = "{\"hello\":0,\"world\":\"0\"}";
    JsonElement json = parser.parse(responseJson); // Omits error checking, what if responseJson is invalid JSON?
    System.out.println(gson.toJson(new TestResponse(json)));
    

This should print:

{
  "response": {
    "hello": 0,
    "world": "0"
  }
}

It should also work for any valid JSON:

String responseJson = "{\"arbitrary\":\"fields\",\"can-be\":{\"in\":[\"here\",\"!\"]}}";
JsonElement json = parser.parse(responseJson);
System.out.println(gson.toJson(new TestResponse(json)));

Output:

{
  "response": {
    "arbitrary": "fields",
    "can-be": {
      "in": [
        "here",
        "!"
      ]
    }
  }
}
like image 92
nickb Avatar answered Oct 13 '22 01:10

nickb