Removing backslash from JSON format while programmatically constructing a JSON array - java

I want to parse the JSON data by removing the backslash from the JSON format.
I have tried removing the backslash from the JSON format by the following code but nothing worked out
JSONArray packsJSON = new JSONArray();
JsonObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JsonObject();
innerObject.addProperty("pack_id",packageList.getSubs_id());
innerObject.addProperty("pack_dsc", packageList.getSubs_desc());
innerObject.addProperty("pack_tax_amt", packageList.getTax_amnt());
innerObject.addProperty("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}
output of INNEROBJECT:
{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}
The output of PACKJSON:
[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}",
"{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"
]
[
"{"pack_id":"39","pack_dsc":"350 Package","pack_tax_amt":"0","pack_grand_total":"419"}",
"{"pack_id":"2232","pack_dsc":"Bangara(280)","pack_tax_amt":"0","pack_grand_total":"280"}"
]

Your JSONArray is of org.json package and JsonObject is of com.google.gson package
so your innerObject's type should be org.json.JSONObject
JSONArray packsJSON = new JSONArray();
JSONObject innerObject;
for(PackageList packageList:selecteditem)
{
innerObject=new JSONObject();
innerObject.put("pack_id",packageList.getSubs_id());
innerObject.put("pack_dsc", packageList.getSubs_desc());
innerObject.put("pack_tax_amt", packageList.getTax_amnt());
innerObject.put("pack_grand_total", packageList.getSubs_grnd_tot_prc());
Log.i("INNEROBJECT","hyu"+innerObject);
packsJSON.put(innerObject);
Log.i("PACKJSON","nkd==>>"+packsJSON)
}

Please check below answer.
String jsonString = "[ "{\"pack_id\":\"39\",\"pack_dsc\":\"350 Package\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"419\"}","{\"pack_id\":\"2232\",\"pack_dsc\":\"Bangara(280)\",\"pack_tax_amt\":\"0\",\"pack_grand_total\":\"280\"}"]"
String outputString = jsonString.replaceAll("\\\\", "");
Log.e("Clear String :", outputString);
OUTPUT

Related

How to remove extra escaping quote characters of JsonObject created through Javax

I use javax to create JsonObject and JsonArray from my List<String> and I have a list of Json objects that i want to put in a JsonObject through a JsonArray
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String Obj : listOfJsonDfObjects)
jsonArray.add(summaryObj); //{"a":"b"},{"c":"d"}
// this line introduces extra escaping quotes like this {"\"a\"":"\"b\""},{"\"c\"":"\"d\""}
javax.json.JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
How to avoid these extra quotes escaping characters?
Thanks
You say you have a list of JSON objects, but you really have a list of JSON-formatted strings. To add them to a JsonArray, you need to parse each one into the JSON object model:
public class JsonTest {
public static void main(String[] args) {
List<String> listOfJsonDfObjects = List.of(
"{\"a\":\"b\"}",
"{\"c\":\"d\"}"
);
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for (String summaryObj : listOfJsonDfObjects) {
JsonReader parser = Json.createReader(new StringReader(summaryObj));
jsonArray.add(parser.readObject());
}
JsonObject data = Json.createObjectBuilder()
.add("data", jsonArray.build()).build();
System.out.println(data); // {"data":[{"a":"b"},{"c":"d"}]}
}
}
Using Gson
Gson gson = new Gson();
String json = gson.toJson(listOfJsonDfObjects);
//check json
System.out.println(json);
json = json.replaceAll("\\\\", "");
json = json.replaceAll("\"\\{", "{");
json = json.replaceAll("\\}\"", "}");
//valid json now
System.out.println(json);
A more secure way (to avoid altering original data)
//concatenate objects in list with comma
String json = String.join(",", listOfJsonDfObjects);
//convert to pseudo array
json = "[" + json + "]";
//convert pseudo json array to pseudo json object
json = "{\"data\":" + json + "}";
//cast to json object
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject);

how to print nested json-object without escapes and quotation marks

i have a json-object named jsonObject
{
"action":"Read",
"infos":[
{
"value":0.0350661,
"key":"first"
}
]
}
i wanna to print the json-object to with the following form
{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}
if i use jsonObject.toString() method i will get
{"action":"Read","infos":"[{\"value\":0.0350661,\"key\":\"first\"}]"}
if i use StringEscapeUtils.unescapeJava(jsonObject.toString()) method i will get
{"action":"Read","infos":"[{"value":0.0350661,"key":"first"}]"}
if i use jackson mapper with the following code
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
String jsonString = mapper.writeValueAsString(getDebugInfo())
i will get jsonString as
{"nameValuePairs":{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}}
is there any solution to get the desired output json-string?
JSON Structure
You have that as an object, that is why quotes are not present there.
In your example, an array object is present, at the Json structure.
Code/Java
While printing at Console, the json body's every Key & Value toString() are referred .
That is why the Double Quotes present, as Strings are getting used!
Here I have tried the below code using GSON library, and it is printing me the correct json as shown above.
public static void main ( String [] args ) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("action", "Read");
JsonArray jsonArr = new JsonArray();
JsonObject jsonObject2 = new JsonObject();
jsonObject2.addProperty("value", 0.0350661);
jsonObject2.addProperty("key", "first");
jsonArr.add(jsonObject2);
jsonObject.add("infos", jsonArr);
String jsonString = jsonObject.toString();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement json = gson.fromJson(jsonString,JsonElement.class);
String jsonInString = gson.toJson(json);
System.out.println(jsonInString);
}
OUTPUT:
{
"action": "Read",
"infos": [
{
"value": 0.0350661,
"key": "first"
}
]
}
Even if I am forming the jsonObject using org.json, and simple printing it using System.out.println(jsonObject.toString()); on console, m getting the result like this.
{"action":"Read","infos":[{"value":0.0350661,"key":"first"}]}
So here, not sure how you have formed your jsonObject.

Parsing JSON fails with not a JSONArray

I am trying to parse the following JSON in Java program.
JSON
{
"data": {
"pageIDentifier":" nametitle",
"page": {
"pageID”:” sports_league_member",
"platform":" www",
"activityType":" ent",
"businessUnit":" ent",
"productLOB":" ent",
"productOffered":" abc",
"productQualifier”:” abc:a bc”,
"flowType”:” sports_com”,
"pageDesc”:” desc”,
"attributes": {
"pageType":" www",
"host”:” finaluser”,
"appId”:” SportsAppID_user”,
"daEnvironment”:” releaser”,
"jvm":" ent_logon_01",
"xCKey":" SportsAppID_user",
"daUID":" jddc9yu5pi1yy6",
"sysEnv”:” user”,
"uri”:” /www/sportscenter”,
"daPageName":" "
}
}
}
}
JAVA Program
URL url = getClass().getResource("test.json");
File file = new File(url.getPath());
String jsonData = readFile(file.getAbsolutePath());
JSONObject jobj = new JSONObject(jsonData);
JSONArray jarr = new JSONArray(jobj.getJSONArray("data").toString());
System.out.println("jarr: " + jarr);
I am getting the following error when executing this code. Please note, jsonData is giving the entire json string without any issue.
org.json.JSONException: JSONObject["data"] is not a JSONArray.
How can i parse "data" value from the above json value? Please advise.
data is not an array
Try this :
System.out.println("jarr: " + jobj.getJSONObject("data").toString());

Remove back slash from Json String in android

i need some help for Remove Back slash from Json String.
Here is the Response which i Get From Server side.
"response":"{\"time_zone\":\"\",\"session_token\":\"abcdefgHijklomopqrstuvwxyz\",\"user_login\":\"abc\",\"user_profile_img\":\"http://jhjhjhj.org/system/photos/62/medium/images.jpg?1462446436\",\"success\":\"0\",\"org_admin\":\"\",\"user_id\":\"62\",\"user_org_id\":\"101\",\"phone_mobile\":\"510-427-9639\",\"user_email\":\"abc#pdmoffice.com\"}"}
what i have don for Remove Backslash from this String
result.replaceAll("\\","");
than After it will give me This String which is not in Json Formate.
{"response":"{"time_zone":"","session_token":"nskfndkjfsfsdffjsdfd","user_login":"newoff2","user_profile_img":"http://absdds.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9639","user_email":"hjhjh#pdmoffice.com"}"}
it Give me Exaption
org.json.JSONException: Unterminated object at character 17 of
{"response":"{"time_zone":"","session_token":"kjshhdscncnxzcxclx","user_login":"newoff2","user_profile_img":"http://abcd.org/system/photos/62/medium/images.jpg?1462446436","success":"0","org_admin":"","user_id":"62","user_org_id":"101","phone_mobile":"510-427-9898","user_email":"sdgas#pdmoffice.com"}"}
How Can i remove this Back slash with Proper Json Formate ?
Thanks in advance
The command
result.replaceAll("\\","");
is correct and if you try to display the server response with an online json formatter (https://jsonformatter.curiousconcept.com/) you can clearly see that the string is not correctly formatted. The double quotes after the "response" and one at the end are not required.
UPDATED: August 2019
Use google's Gson for parsing to Json by omitting backslash automatically:
JAVA CODE:
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse("your jsonString with backslash").getAsJsonObject();
KOTLIN CODE:
val jsonParser = JsonParser()
val jsonObject = jsonParser.parse("your jsonString with backslash").asJsonObject
An alternative to remove backslashes from JSON string.
s = Your String with Back Slash
For converting String to JSONObject:
JSONObject jsonObject = new JSONObject(s);
For converting String to JSONArray:
JSONArray jsonArray = new JSONArray(s);
You can try this and it will work fine
String jsonStr4 = jsonStr3.replaceAll("\"", "");

how to parse a JSON string which is inside a array

I have a json of following format:
{
"Result": {
"question": "Barack Obama vs Mitt Romney?",
"option": [
"Barack Obama",
"Mitt Romney",
"Other"
],
"percentage": [
20,
40,
80
]
}
}
and I am using following code to parse it but this giving null pointer exception at option array.
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONObjectFromUrl(url);
Log.e("json",json.toString());
Log.e("-------url-------", ""+url);
String resultStr = json.getString("Result");
Log.e("result string ",resultStr);
JSONObject jsonObject2 = new JSONObject(resultStr);
String question_string = jsonObject2.getString("question");
Log.e("question String ",question_string);
String option_str = jsonObject2.getString("option");
JSONArray optionArray = new JSONArray(option_str);
Log.d("option array", String.valueOf(optionArray.length()));
You need to get the json array this way:
JSONArray optionArray = jsonObject2.getJSONArray("option");
Log.d("option array", String.valueOf(optionArray.length()));
check http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Use:
JSONArray optionArray = jsonObject2.getJSONArray("option");
as "option" key points to an array and not to a String.
You're going way too complicated here, and not using those lovely GetJSONObject and getJSONArray functions, which will cause you to double parse a lot. Try this
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONObjectFromUrl(url);
Log.e("json",json.toString());
Log.e("-------url-------", ""+url);
JSONObject jsonObject2 = json.getJSONObject("Result");
String question_string = jsonObject2.getString("question");
Log.e("question String ",question_string);
JSONArray optionArray = jsonObject2.getJSONArray("option");
Instead of using
String option_str = jsonObject2.getString("option");
use this :
JSONARRAY optionArray = jsonObject2.getJSONAray("option");
for(int i=0;i<optionArray.length; i++){
String option = optionArray[i].getString();}
Try this..

Categories

Resources