Android - convert json string to JSONObject without removing the escaped characters [duplicate] - android

This question already has answers here:
conversion from string to JSON object Android
(9 answers)
Closed 5 years ago.
I convert json string to JSONObject using JSONObject jsonObject = new JSONObject(jsonString); And the convert jsonObject to Java Object using gson
But it gives an error when a json attribute value contains quotes,
like , { "length" : "10"" } (its, 10 inches)
Edit :
i get data from server api in following manner :
"{\"data\":\"10\"\"}"
i replace \" by ", and which converts into { "data" : "10"" }
this gives exception as it cannot convert jsonobject into java object
org.json.JSONException: Unterminated object at character 13 of {"data":"10""}
How can i convert "{\"data\":\"10\"\"}" to { "data" : "10\"" }
Edit 2 :
I was converting the string to JSONObject the wrong way.
By removing slashes, I was also removing the slashes of escaped characters.
Solution : Instead, I used StringEscapeUtils.unescapeJson(jsonString) which didn't remove the slashes of escaped characters inside json key-value data.

You have to use \ escape character before ". Here's what you should do:
{ "length" : "10\"" }
If you have to use special character in your JSON string, you can escape it using \ character.
See this list of special character used in JSON :
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character

Please share your error as well.
As far as from your Question i can see there are 2 quotes near 10.
{ "length" : "10"`"` }
If you want to insert " for inches please provide \".

Try this
jsonString = "{\"data\":\"10\"\"}";
String jsonFormattedString = jsonString.replaceAll("\\\\", "");
Log.i("Response",":"+jsonFormattedString);
OUTPUT
I/Response: :{"data":"10""}
EDIT
jsonString = "{\"data\":\"10\"\"}";
String jsonFormattedString = downloadDetails.replaceAll("\"", "");
Log.i("Response",":"+jsonFormattedString);
JSONObject jsonObject = new JSONObject(jsonFormattedString);
String data = jsonObject.getString("data");
Log.i("Response data",":"+data);
OUTPUT
I/Response: :{data:10}
I/Response data: :10
LAST EDIT
jsonString = "{\"data\":\"10\"\"}";
String jsonFormattedString = downloadDetails.replaceAll("\"", "");
Log.i("Response",":"+jsonFormattedString);
final String regex = "([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)";
final String subst = "\"$1\":\"$2\"";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(jsonFormattedString);
jsonFormattedString = matcher.replaceAll(subst);
Log.i("Final Response",":"+jsonFormattedString);
JSONObject jsonObject = new JSONObject(jsonFormattedString);
String data = jsonObject.getString("data");
Log.i("Response data",":"+data);
data = data+"\"";
Log.i("FINAL VALUE",":"+data);
LAST OUTPUT
I/Response: :{data:10}
I/Final Response: :{"data":"10"}
I/Response data: :10
I/FINAL VALUE: :10"

Related

How to get this data in json fromat?

I got this data in PayUMoney and to show the user But problem how to get this data in json or key value pair format any one know that please help!!
addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&
Assuming that u have got it as String following code will print the key value pair from the string
String x ="addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&";
String pair[] = x.split("&");
Log.e("pairs", Arrays.asList(pair).toString());
for (int i=0;i<pair.length;i++){
String key[] = pair[i].split("=");
Log.e("pair:","key= "+ key[0]+" value= "+key[1]);
}
It seems the string is both URL encoded (the %3A) and JSON encoded (the &).
You have to decode the string and then split by '&' and then split each pair to key and value by '='.
You can see here how to JSON decode: Decoding JSON String in Java
URL decoding can be done with Java's URLDecoder class: https://docs.oracle.com/javase/7/docs/api/java/net/URLDecoder.html
For this example I'll just assume the only encoded characters are %3A and &.
String payumoney = "addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&";
// String decoding.
payumoney = payumoney.replaceAll("%3A", "-");
payumoney = payumoney.replaceAll("&", "&");
HashMap<String, String> params = new HashMap<String, String>();
String[] pairs = payumoney.split("&");
for (String pair : pairs) {
String[] keyValue = pair.split("=");
params.put(keyValue[0], keyValue[1]);
}
This looks like a String with mixture of URL encoding (like %3A for :) and HTML characters (like & for &).
I believe you can try decoding it and then split data like say by & to get data for each key and then further split by = to get value for that key.
For URL decoding you can try like
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
You can simply use String replaceAll() function to create the json.
str= str.replaceAll("=", "\"");
str= str.replaceAll("&", "\",\"");
str= "{\""+ str+ "\"}";

Error invalid int when parsing JSONObject into an integer

Basically I want to convert a JSONObject json into an integer (127181078). When I use this code:
int intOfReceivedID = Integer.parseInt(json);
I get this error message:
java.lang.NumberFormatException: Invalid int: 127181078"
When I use this code:
char[] charArray = json.toCharArray();
String stringCharArray = charArray.toString();
testTextView.setText(stringCharArray);
testTextView gives me: [C#2378e625
However, when I use this code:
preprocessedjson = String.valueOf(json);
testTextView.setText(preprocessedjson);
The TextView gives 127181078, but I get the some error when I parse the text to an integer.
Can anybody tell me what going on here?
And could you help me convert my JSONObject into an integer?
This is the php code:
$myfile = fopen($filename, 'r') or die("Unable to open file!");
echo fread($myfile,filesize($filename));
fclose($myfile);
This is the the makeHttpRequest:
JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
This question is confusing but from your error message it looks like this is a Java question that has nothing to do with JSON since your json String in this case looks like it does not in fact contain json(from the exception message).
It looks like the issue is your json value is a number plus additional spaces which Integer.parseInt does not handle.
Try
Integer.parseInt(json.trim())
int intOfReceivedID = Integer.parseInt(json);
I get this error
message:
java.lang.NumberFormatException: Invalid int: 127181078"
This happens because there is a new-line character at the end of the ID which can not be parsed into an Integer.
When I use this code:
char[] charArray = json.toCharArray();
String stringCharArray = charArray.toString();
testTextView.setText(stringCharArray);
testTextView gives me: [C#2378e625
By default, calling toString() on an object prints the memory location of the object (in this case [C#2378e625). That's what's being displayed in the TextView.
However, when I use this code:
preprocessedjson = String.valueOf(json);
testTextView.setText(preprocessedjson);
The TextView gives 127181078, but I get the some error when I parse
the text to an integer.
You'll get an error when parsing the text to an integer because it still has an invalid new-line character at the end.
If you are receiving a JSONObject from the server which only contains a long, then you can use the getLong() or optLong() methods to retrieve the integer value. The JSON parser automatically handles all the parsing and you don't need to do any additional work.
JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
final long receivedId = json.optLong();

Retrofit: Parse unicode characters in json

I have some UNICODE characters in my response like this:
"city": "Bel\\u00e9m"
and it is parsed like this:
city = "Bel\u00e9m"
But i expect it to be:
city = "Belém"
What is going wrong here and what should i do to have a properly parsed unicode character in my response?
String auto convert unicode characters to letters.
So save your response to a string variable and then make JSON from that string object.
String myString = "city": your json response;
then make json object from myString
JSonObject obj = new JSonObject(myString);
may it help you.
try this out,
Html.fromHtml(city.replaceAll("\\","\"));

Android Convert String to JSONObject

I want to convert a string to JSONObject. Below is sample code.
String str = "{"time": 1449838598.0999202, "Label": "Shirt", "Price": 52}";
JSONObject obj = new JSONObject(str);
But after conversion time becomes 1.4498385980999203E9.
Any Help will be appreciated.
Thanks
If you really want it to be formatted like that then make it into a string instead of a number. Just add double quotes around the item. But if your using it for a calculation on the other end, i would leave it as is as you'll have to convert it back to a int anyway. If you want to use gson as an alternative check here: How to prevent Gson from converting a long number (a json string ) to scientific notation format?
Write it like this in double quote. "1449838598.0999202"
Like Abhishek said, write time & price in double quote as "1449838598.0999202" and "52".
Then you can save the string to Gson, and then convert it to Json.
String str = "{"time": "1449838598.0999202", "Label": "Shirt", "Price": "52"}";
Gson gson = new Gson();
String json = gson.toJson(str);

Not able to get name/value pairs from JSON object, when using variable

Not able to get name/value pairs from JSON object, when using the variable but able to read it when hard coding the name.
To better explain :
1) My JSON object is like this -
{.....
{ "rates":{ "name1": value1, "name2": value2 ...etc }
...}
2) I am able to read this object in my android app.
3) Now this rate object name value pairs, i am trying to read based on user input -
String s1 = '"'+name1+'"'; // here name1 i got from user input, & converted into string
4) Now when i am trying to get the value from rates object, i am getting null exception -
JSONObject rateObject = jObject.getJSONObject("rates"); //able to get
complete object
String rate1 = (String) rateObject.get(s1); // giving NULL exception
5) But if i use hard code string, it works -
String rate1 = (String) rateObject.get("name1"); // working
Any pointers why its not working while using variable.
thanks
Thanks for suggestions, i sorted out the problem. There are 2 mistakes i was doing - 1) Using the quotes as correctly pointed out by others and 2) casting the double value to string. Correcting both has resolved my problem :)
In terms of your final code snippet, you are actually doing
String rate1 = (String) rateObject.get("\"name1\""); //note the extra quotes
because you have bookended the user input string with double-quote characters. You just want the input string itself with no bookending. The quotes in the JSON notation serve to delineate each key name; the quotes are not part of the key name itself.
You need to omit the quotes when you create s1:
String s1 = name1;
Or, if name1 is not a String already:
String s1 = name1.toString();
Replace:
String s1 = '"'+name1+'"';
with:
String s1 = name1;

Categories

Resources