I am trying to Sanitize the requestBody. For this purpose I am converting Object to Json and then passing the Json to
requestBody
{
"data": {
"id": "123",
"unit_id": "456",
"country": "jp",
}
}
StringEscapeUtils.escapeHtml
Output post escaping:
{"data":{"id":"123","unit_id":"456","country":"jp"}}
It is escaping the double quotes(“) which is breaking the Json structure when I am trying convert the Json back to Object.
How I can exclude double quotes(“) alone during this process?
Related
I am new in Java coding, I am trying to post a JSOn file, here is my JSON file object
{
"report": "[{\"patientId\":\"abcd-efg\",\"campaignId\":\"2\",\"phoneCallsMade\":\"[]\",\"message\":\"[]\"}, {\"patientId\":\"abcd-efg\",\"campaignId\":\"2\",\"phoneCallsMade\":\"[]\",\"message\":\"[]\"}]"
}
I am trying to remove the backslash, I tried below methods :
myJsonString.replaceAll("\\","");
myJsonString=myJsonString.replaceAll("\\\\","");
but after doing that the json format is not valid. Can someone help me please.
This is just a string not a json array. And the reason of getting invalid json post removing slashes is due to in correct mapping of double quotes. Just remove double quotes from "[ & ]" from beginning and from end and perform the operation. Your problem will be resolved.
{
"report": [{
"patientId": "abcd-efg",
"campaignId": "2",
"phoneCallsMade": "[]",
"message": "[]"
}, {
"patientId": "abcd-efg",
"campaignId": "2",
"phoneCallsMade": "[]",
"message": "[]"
}]
}
This will be the output.
Sometime client send Json-RPC request with Json value as unicorde symboles.
Example:
{ "jsonrpc": "2.0", "method": "add", "params": { "fields": [ { "id": 1, "val": "\u0414\u0435\u043d\u0438\u0441" }, { "id": 2, "val": "\u041c\u043e\u044f" } ] }, "id": "564b0f7d-868a-4ff0-9703-17e4f768699d" }
How do I processing Json-RPC request:
My server get the request like byte[];
Convert it to io.vertx.core.json.JsonObject;
Make some manipulations;
Save to DB;
And I found in DB records like:
"val": "\u0414\u0435\u043d\u0438\u0441"
And the worst in this story. If client try to search this data, he'll get:
"val": "\\u0414\\u0435\\u043d\\u0438\\u0441"
So I think, that I need to convert request data before deserialization to JsonObject.
I tried and it didn't help:
String json = new String(incomingJsonBytes, StandardCharsets.UTF_8);
return json.getBytes(StandardCharsets.UTF_8);
Also I tried to use StandardCharsets.US_ASCII.
Note: Variant with StringEscapeUtils.unescapeJava() I can not, because it unescape all necessary and unnecessary '\' symbols.
If anyone know how to solve it? Or library that already makes it?
Thank a lot.
io.vertx.core.json.JsonObject depends on Jackson ObjectMapper to perform the actual JSON deserialization (e.g. io.vertx.core.json.Json has a ObjectMapper field). By default Jackson will convert \u0414\u0435\u043d\u0438\u0441 into Денис. You can verify this with a simple code snippet:
String json = "{ \"jsonrpc\": \"2.0\", \"method\": \"add\", \"params\": { \"fields\": [ { \"id\": 1, \"val\": \"\\u0414\\u0435\\u043d\\u0438\\u0441\" }, { \"id\": 2, \"val\": \"\\u041c\\u043e\\u044f\" } ] }, \"id\": \"564b0f7d-868a-4ff0-9703-17e4f768699d\" }";
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(json, Map.class);
System.out.println(map); // {jsonrpc=2.0, method=add, params={fields=[{id=1, val=Денис}, {id=2, val=Моя}]}, id=564b0f7d-868a-4ff0-9703-17e4f768699d}
Most likely the client is sending something else because your example value is deserialized correctly. Perhaps it's doubly escaped \\u0414\\u0435\\u043d\\u0438\\u0441 value which Jackson will convert to \u0414\u0435\u043d\u0438\u0441 removing one layer of escaping?
There is no magic solution for this. Either write your own Jackson deserialization configuration or make the client stop sending garbage.
I am looking for some Java library, which can convert below give String into Json object.
Input: String reading from file.
{ "product": "{\"sku\":\"rtwre-rtwe\",\"price\":\"50.90\",\"currency_code\":\"SGD\",\"quantity\":1}", "is_organic": "0", "can_claim": "0", "t": "r", "device": "Phone", "amount_transactions": "0" }
Expected output: In some generic Java Json object.
{
"product": {
"sku": "rtwre-rtwe",
"price": "50.90",
"currency_code": "SGD",
"quantity": 1
},
"is_organic": "0",
"can_claim": "0",
"t": "r",
"device": "Phone",
"amount_transactions": "0"
}
Imp points: This is sample code, I have more dynamic json and don't have any Java object corresponding to my json. I can have string json in any key. It's not specific to particular key. I am looking for more generic code.
Here my goal if I read value of key "product" it should return Json instead of String. I want to read $.product.price using JsonPath library. http://jsonpath.com/
Edit1: I don't have much experience with Gson, Jackson and JsonObject libraries, but I tried whatever I could do. If you had handled the same scenario, please help me out.
To resolve it you can use :
JSONObject jsonObj = new JSONObject(myStringValue);
String myJsonStructureAsString = jsonObj.toString();
Where JSONObject is org.json.JSONObject form lib json-org.v2017.05.16.jar
I would like to trim the below json object. That is a json object I built on top of what mongoDB responded. What I want to do is to remove just $oid because they are redundant attributes and keep the value inside (_id or $id ) without Curley braces and simply call the attribute id.
so what I need is just "id": "2283cef627ff2cc33ad5990"
Could you please help me I am struggling with json.
{
"_id": {
"$oid": "22383cef627ff2cc33ad5990"
},
"name": "data1",
"users": [
{
"$ref": "user",
"$id": {
"$oid": "16a5fbcee4b0c2c2da3017ef"
}
},
{
"$ref": "user",
"$id": {
"$oid": "1795ff86e4b09fc66416cd2f"
}
},
],
},
a) You can use a mapper to convert your JSON to an object and then call the desired attribute, like Jackson:
ObjectMapper mapper = new ObjectMapper();
String jsonInString = YOUR_STRING;
//from String to MyClass
MyClass object = mapper.readValue(jsonInString, MyClass.class);
In this example you have to define a class MyClass with all the attributes you need (e.g. _id, name, users, etc).
b) If you want to implement a quicker solution you can manipulate directly the string; if you know that the oid is always 24 characters you can do something like
String c = str.substring(str.indexOf("\"", str.indexOf("$oid")+6)+1, str.indexOf("\"", str.indexOf("$oid")+6)+25);
but I highly recommend to take a look to Jackson and give it a try. A solution like this is very fragile and every change in the JSON will lead to a wrong result.
I want to generate a JSON String in the following structure using Jackson API (JsonFactory,JsonGenerator). How can i do it ?
Expected:
{
"api": {
"Salutaion": "Mr",
"name": "X"
},
"additional": {
"Hello",
"World"
}
}
Actual:
{
"api": "{
\"Salutaion\": \"Mr\",
\"name\": \"X\"
}",
"additional": "{
\"Hello\",
\"World\"
}"
}
The values of the attributes api & additional will be available to me as String. Should i be using writeObjectField (as follows) ?
jGenerator.writeObjectField("api", apiString);
After constructing the jGenerator object, how do i get the final constructed JSON Object's String representation ?
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator jGenerator = jfactory.createJsonGenerator(outputStream);
jGenerator.writeStartObject();
jGenerator.writeObjectField("api", apiString);
jGenerator.writeObjectField("additional", additionalString);
jGenerator.writeEndObject();
jGenerator.close();
outputStream.close();
outputStream.toString()
The outputStream.toString() gives a json string but the double quotes (") in the apiString are getting prefixed with an escape character \
Is this the right way ?
Assuming apiString and additionalString are references to String objects with JSON content, you'll want to write them raw, ie. their content directly. Otherwise, you're serializing them as JSON strings and Jackson will need to escape any relevant characters.
For example
jGenerator.writeFieldName("api");
jGenerator.writeRawValue(apiString);
for api, and the same for additional.