Tiya
Tiya

Reputation: 563

Gson Json conversion adding extra back slash

I am working on a service that has the following code (I can change this code):

import com.google.gson.JsonObject;
import com.google.gson.Gson;

Gson gson = new Gson();
JsonObject json = new JsonObject();
json.addProperty("customer", gson.toJson(customer));
anotherServiceClient.dispatch(json.toString());

AnotherService Class code has a dispatch method implementation that takes in a String object and adds it to a json where party is a String. I can't change this code.

    JsonObject json = new JsonObject();
    json.addProperty("party", inputCustomerJson);

I need the anotherService to have the output like:

"party": "{\"customer\":\"{\"id\":\"A123\"}"}

but instead it is :

"party": "{\"customer\":\"{\\\"id\\\":\\\"A123\\\"}"}

Upvotes: 0

Views: 2057

Answers (1)

Marcono1234
Marcono1234

Reputation: 6894

The problem is this line:

json.addProperty("customer", gson.toJson(customer));

Gson.toJson produces a JSON string as output ("{\"id\":\"A123\"}"), so when you then later serialize this data again as JSON the backslashes and double quotes are escaped.

Most likely you want to use Gson.toJsonTree and JsonObject.add(String, JsonElement):

json.add("customer", gson.toJsonTree(customer));

Upvotes: 2

Related Questions