Removing escape characters in json using Java - java

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.

Related

Excluding “ when using StringEscapeUtils.escapeHtml4

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?

How to convert nested Json in string into Json object in java

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

Java: Gson parse without square brackets

I have a JSON file that I'm trying to parse that doesn't have surrounding square brackets: [...].
Here is the Java code. (This has the Gson dependency in Maven) I keep on getting the error on line 29, "This is not a JSON Array." However, when I add square brackets to the beginning and end of the JSON file, it parses just fine. How can I parse this without the brackets.
Here is the JSON:
{
"title": "Title",
"content": "whatever",
"author": "Yuki Noguchi",
"date_published": "2017-02-15T20:25:00.000Z",
"lead_image_url": "https://media.npr.org/assets/img/2017/02/15/ap_17039860769171_wide-d1a5d3c17f00d78fd1df9d19a96e1d7b3bd38e60.jpg?s=1400",
"dek": null,
"next_page_url": null,
"url": "http://www.npr.org/2017/02/15/515425370/trump-labor-pick-andrew-puzders-nomination-appears-in-jeopardy",
"domain": "www.npr.org",
"excerpt": "The fast-food CEO faced fierce opposition from labor groups, plus personal controversies. Ultimately, he didn't have support from enough Republican senators.",
"word_count": 751,
"direction": "ltr",
"total_pages": 1,
"rendered_pages": 1
}
Thanks!
Try this one, append "[" open and "]" close braces and store in temporary variable and pass that temporary variable to parse.
for example,
var jsonVar = { name:"hello", title: "WOrld" };
var tmpJsonVar = "[" + jsonVar + "]";
var jsonObject = JSON.parse(tmpJsonVar);

Unwanted character \\\r is appearing in json response from rest api

I have written a few rest services to extract data from a mysql database and display it in json format on Postman client. However for some of the response items, I get this unwanted \\r character in the response values. For example:
{
"colour": "yellow",
"deliveryCharge": 5,
"description": "Mangoes from Ratnagiri",
"keyFeatures": [
"Seedless\\\r",
"Ripe and Sweet"
],
"price": 100,
"productId": 49,
"productName": "Alfonso",
"specifications": {
"entry": [
{
"key": "Feature",
"value": "N/A"
}
]
},
"stock": 20,
"warranty": 1
}
How do I get rid of these characters in the final json response? I have tried isolating them using .replace() and .split() methods for the output strings fetched from the database, but it doesn't work.
You have two escaped character \ and \r in the string. trim method in String class can remove \r but not \. If you don't want to send these character, You will have to do it yourself before serializing the objec to to JSON.

MarkLogic Query By Example - underscore in JSON key not working?

I have the following entry in MarkLogic in JSON format:
{
"identifier":"user1",
"attributesList": [
{
"firstName": "James",
"address_1": "Farcity"
}
]
}
If, I'm going to query that using the below format:
{
$query:
{
"identifier":"user1",
"attributesList": [
{
"firstName": "James"
}
]
}
}
this will match and return back the expected result with a count of 1 because "firstName" is equal to "James".
However, if I do the following:
{
$query:
{
"identifier":"user1",
"attributesList": [
{
"address_1": "Farcity"
}
]
}
}
it will not give back any result even if "address_1" exactly matches which is "Farcity". I already tried this on other JSON key as well, it works fine with all except those with underscores in the key.. Is this a reserved character? If so, is there a way to escape this so that the key "address_1" or "county_state" can still be matched?
It looks like the Json object converts the underscores to a double underscore
running this:
xquery version "1.0-ml";
import module namespace json="http://marklogic.com/xdmp/json"
at "/MarkLogic/json/json.xqy";
let $j :=
'{
"identifier":"user1",
"attributesList": [
{
"firstName": "James",
"address_1": "Farcity"
}
]
}'
return
json:transform-from-json( $j)
you will get this out put
<json type="object" xmlns="http://marklogic.com/xdmp/json/basic">
<identifier type="string">user1</identifier>
<attributesList type="array">
<json type="object">
<firstName type="string">James</firstName>
<address__1 type="string">Farcity</address__1>
</json>
</attributesList>
</json>
So try querying with a double underscores. Also If you are using Marklogic 6 or 7 it converts the Json to xml. so you could just try to query by example using the XML format.
See http://docs.marklogic.com/xdmp:encode-for-NCName for the exact algorithm and function used to map JSON field names to QNames

Categories