Remove back slash from Json String in android - java

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("\"", "");

Related

Removing backslash from JSON format while programmatically constructing a JSON array

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

Can't use (google.gson) jsonParser to parse string as jsonObject

I want to parse my string input as a json and then get items from it for this reason i have added this code:
String data=new String(content.getBytes(),"UTF-8");
String x=data.replaceAll("[\\n\\r\\t]+", "");
System.out.println(x+"=================================================");
FormatedData="id:"+id+"\n"+"name:"+name+"\n"+"comment:"+comment;
String id,name,comment;
JsonParser parser = new JsonParser();
System.out.println(x+"===================================================");
JsonObject obj = (JsonObject) parser.parse(x).getAsJsonObject();
System.out.println(obj+"===============================================");
name = obj.get("organizationNameEN").getAsString();
id = obj.get("id").getAsString();
comment=obj.get("comment").getAsString();
String FormatedData="id:"+id+"\n"+"name:"+name+"\n"+"comment:"+comment;
here is my JsonData:
{id:15, organizationNameGE:55, organizationNameEN:5656, cardNumber:6767, startDate:02/04/2018, period:5, endDate:02/10/2018, priority:not so important, $$hashKey:19A, comment:comment, mail:mail}
I am useing this library for parsing com.google.gson.JsonParser; but when i try to make this operation i got this error:
com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 89 path $.startDate
I HVAE REMOVED ALL SPACES FROM STRING WHAT SHOULD I CHENAGE HERE TO GET RID OF THIS ERROR?

Add double quotes to some part of a dynamic string

I have a String. I am converting to JSonObject then to JSONArray. But the string is not a perfect JSONObject. I am trying to convert it to a perfect JSONOBject by adding double quotes to ids and States but i am not sure how to do that. Need some suggestions please.
String jsonString = "{
\"userDetails\": {
ids: [\"1\", \"2\"],
States: [\"TX\", \"PA\"]
}
}";
JSONObject obj = new JSONObject(jsonString);
JSONObject obj1 = new JSONObject("userDetails");
String array = obj1.getJSONArray("HE_SUBJECT").toString();
But here its not a perfect JSONObject as ids and States doesnt have the double Quotes. Here i have the string directly but i will be getting the string dynamically. So not sure how i can add double quotes after i can get the jsonString. Need some help please.
just use online http://www.freeformatter.com/java-dotnet-escape.html , just paste your string it will give string in correct escaped format.
Not sure if this is a good way but i am replacing ids with "ids" like:
jsonString.replace("ids","\"ids\"");

How to consume/deserialize .Net WCF service JSON response in Java

I am having problem while consuming/deserializing WCF .NET JSON response in Java. JSON response is in the following format.
{"d":"[
{\"ID\":123,\"Company\":\"Microsoft\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.microsoft.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"},
{\"ID\":124,\"Company\":\"Google\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.google.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"},
{\"ID\":125,\"Company\":\"Apple\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.abc.com\",
\"FirstName\":\"john\",\"Email\":\"abc#gmail.com\"}
]"}
While on the Java code side I am having problem to deserialize this json response to get out my objects and their corresponding properties.
This is the java code currently I am using to deserialize json response.
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
if (element.isJsonObject()) {
JsonArray companies = element.getAsJsonArray();
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}
Is there any problem in the JSON response format or its right? any kind of help is appreciated, thanks in advance.
I'm not sure why you're getting that response - it't not valid json. There are two things wrong with it
The outer square brackets should not be wrapped in quotes.
The quote escape characters need to be removed (not sure if this is just you putting them in?)
Without you posting the actual error you get (hint: even though stack overflow is powerful, we have not yet developed the ability to read minds) it's very difficult to know what the actual problem is.
Tom is right. Valid JSON should look like this:
{"d":[
{"ID":123,"Company":"Microsoft","Country":"USA",
"website":"http://www.microsoft.com",
"FirstName":"john","Email":"abc#gmail.com"},
{"ID":124,"Company":"Google","Country":"USA",
"website":"http://www.google.com",
"FirstName":"john","Email":"abc#gmail.com"},
{"ID":125,"Company":"Apple","Country":"USA",
"website":"http://www.aabc.com",
"FirstName":"john","Email":"abc#gmail.com"}
]}
And your code like this:
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
JsonObject object = element.getAsJsonObject();
if (object.isJsonObject()) {
JsonArray companies = object.getAsJsonArray("d");
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}

JSON Exception String cannot be converted to JSON Object

I am trying to parse json and running into a small problem.
my json string looks like this:
String json =
[
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}",
"{caption=adsf, url=/storage/emulated/0/DCIM/Camera/20140330_103412.jpg}"
]
and my code so far looks like this:
try {
JSONArray jsonObj = new JSONArray(json);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String img = c.getString("url");
String cap = c.getString("caption");
But its throwing an exception type java.lang.String cannot be converted to JSONObject
What am I doing wrong?
EDIT
If its helpful to anyone, I ended up using GSON to get my json in the correct expected format like this:
Gson gson = new Gson();
String json = gson.toJson(mylist);
Your JSON array contains elements like
"{caption=blah, url=/storage/emulated/0/DCIM/Camera/20140331_164648.jpg}"
which is a String not a JSON object. You can't therefore try to retrieve it as a JSONObject.
Seems like you're getting JSON that isn't in the format you expected. Even if you got rid of the "" around it, it still wouldn't be valid JSON, so I don't understand its purpose enough to help you.

Categories

Resources