Gson Json conversion adding extra back slash - json

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\\\"}"}

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

Related

How to parse single quote special charater using Gson library in Scala

I am unable to parse json file if values contain single quote and other characters as '()= etc
Hi I have the following Json file:
{
"config": {
"inputDFName": "testInput",
"conditions": "site_type = 'micro'"
}
}
The parser class like
case class FilterConfig(inputDFName: String,conditions: String)
I am parsing json using below function
def readDataFilter(conf:String): FilterConfig ={
val gson = new Gson()
gson.fromJson(conf,classOf[FilterConfig])
}
But return error like : com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException
but if i remove single quotes and equal to sign its working fine.
Please help here.
I see two problems here.
inputDFName in JSON is not matching with testDFName in FilterConfig class.
Your JSON structure is different from that of FilterConfig.
I tried to run the code with the above changes and its working fine.
case class FilterConfig(inputDFName: String,conditions: String)
import com.google.gson.Gson;
def readDataFiltr(conf:String): FilterConfig ={
val gson = new Gson()
gson.fromJson(conf,classOf[FilterConfig])
}
val x = readDataFiltr("{\"inputDFName\": \"testInput\", \"conditions\": \"site_type = 'micro'\"}")
println(x.inputDFName)
println(x.conditions)
Please let me know if this is not clear.
Thanks,
Vivek

How to remove escaping slashes from a json inside another json?

I have the following json, that is being populated by:
new Gson().toJson(batch.getProducts());
But when im adding it to my main JSONObject, the fact that it's a value of a json is doing all the json (even the keys) be escaped.
{"name":"Ufud","store":2,"products":"[{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Teste2\",\"stock\":2,\"value\":19.9}]"}
Is there any method to prevent this?
If you're going to manipulate your json in future you may consider converting it not into a string, but into a JsonElement which can be quite easily added to already existing JsonObject
JsonObject mainObject = getMainObject(); //method which creates your main object. You can change it to variable reference
JsonElement productsElement = new Gson().toJsonTree(batch.getProducts()); //converting your object into JsonElement
mainObject.add("products", productsElement); //insering products element into object.
String json = new Gson().toJson(mainObject); //converting object with products element into a json string

Get JSON value from JSON which is type string in Mule data mapper

I am using Mule 3.6.1 and in datamapper I have a JSON object which is a string datatype and I need to get the value of a field from the JSON object.
How can I get this value from the JSON object while the object is of type String?
I cannot use the JSON transformer for this.
Thanks for any help
To convert a String of JSON and get one of its field value inside DataMapper, then you can utilize code like this (in DataMapper Script area):
jsonObject = new org.json.JSONObject(input.jsonstring);
output.jsonValue = jsonObject.getString("jsonfield");
In order to convert JSON element to a series of objects. Google GSon library is very helpful.
Example:
import com.google.gson.Gson;
Gson gson = new Gson();
Student studentTest = gson.fromJson(data, Student.class);
System.out.println("Amount: " + studentTest .getStudentName());

Use a JSON with JSONOBJECT in Java

I want to use the following JSON in my code in Java:
[
{
"speed": 200
}
]
I tried to write this line :
JSONObject jsonBody = new JSONObject("[{\"speed\": 200}]");
But I always get an error. What is the exact format that I have to use here??
EDIT: So it would be more proper to use a JSONArray rather than use a JSONObject (as my last post said)
So the correct java code would be
String json = "[{\"speed\": 200}]";
System.out.println(json);
JSONArray jsonBody = new JSONArray(json);
System.out.println(jsonBody.getJSONObject(0).get("speed"));

JSON, Servlet, JSP

Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).
Can I pass the parameters from the database?
Once the URL is entered, the information returned will be in text format using JSON
format.
The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}
How shall I do this in servlets? doPost()
Just set the proper content type and encoding and write the JSON string to the response accordingly.
String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.
Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)
String json = new Gson().toJson(result);
// ... (just write to response as above)
Jackson is another option for JSON object marshalling.