When I use Gson (JsonParser.parse) to decode the following:
{ "item": "Bread", "cost": {"currency": "\u0024", "amount": "3"}, "description": "This is bread\u2122. \u00A92015" }
The "currency" element is returned as a string of characters (and is not converted to a unicode character). Is there a setting or method in Gson that could help me?
If not, is there any way in Android to convert a string that contains one or more escaped character sequences (like "\u0024") to an output string with unicode characters (without writing my own and without using StringEscapeUtils from Apache)?
I'd like to avoid adding another library (for just one small feature).
Update
Looks like the server was double escaping the back slash in the unicode escape sequence. Thanks everyone for your help!
Is it only me or is it really more complicated than simply using TextView's setText() method? Anyhow, following is working just fine on my end with the given sample json (put the sample to assets and read it using loadJSONFromAsset()):
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(loadJSONFromAsset());
JsonObject obj = element.getAsJsonObject();
JsonObject cost = obj.getAsJsonObject("cost");
JsonPrimitive sign = cost.get("currency").getAsJsonPrimitive();
TextView tv = (TextView)findViewById(R.id.dollar_sign);
tv.setText(sign.getAsString());
Gson returns "$". Something is wrong in your set up.
String s = "{ \"item\": \"Bread\", \"cost\": {\"currency\": "
+ "\"\\u0024\", \"amount\": \"3\"}, \"description\": "
+ "\"This is bread\\u2122. \\u00A92015\" }\n";
JsonElement v = new JsonParser().parse(s);
assertEquals("$", v.getAsJsonObject().get("cost").getAsJsonObject()
.get("currency").getAsString());
You can parse it as a hex number
char c = (char)Integer.parseInt(str.substring(2), 16);
Related
When I set a json string from web service call and it has a £ sign it shows pound;, yen;, and if it has an apostrophe( ' ) it shows '
UPDATED:
json = Empresszulu$£¥€©™ sets as Empresszulu$£¥©&trade, and
don't sets as don#039;t.
NOTE: the json is from mysql so it could be changed to anything anytime.
You need to use "UTF-8" encoding for using this kind of special character.
You have to encode for your expected character like this way :
String data = EntityUtils.toString(response.getEntity(), android.httpclient.protocol.HTTP.UTF_8);
JSONObject jsono = new JSONObject(data);
My web site send a JWT (built in php) to a my app developped in Java.
The JWT contains a JSON String inside a custom field called DATI.
I use the library JJWT in order to decript the string contained inside DATI field:
Claims MY_CLAIMS = Jwts.parser().setSigningKey(SECRET_KEY__Byte).parseClaimsJws(STRING_JWT).getBody();
ArrayList ARRAY = MY_CLAIMS .get("DATI", ArrayList.class);
String DECODED_STRING_INSIDE_DATI =String.valueOf(ARRAY);
I get the string "DECODED_STRING_INSIDE_DATI" (that is a JSON String) in the correct way, but for some reason the quotation marks (") are removed:
[{id=3, id_rivenditore=-1, id_cliente=-1, ip_address=192.168.1.6, nome=DonalDuck, note=ByBye, enabled=1}]
I tested STRING_JWT in "https://jwt.io/", and there I get correctly the quotation marks:
{
"iss": "www.mySite.it",
"exp": 1536913435,
"sub": "WebApp",
"DATI": [
{
"id": "3",
"id_rivenditore": "-1",
"id_cliente": "-1",
"ip_address": "192.168.1.6",
"nome": "DonalDuck",
"note": "ByBye",
"enabled": "1"
}
]
}
I really don't know how to solve it, because I cannot read the JSON string in the right way. I use jackson library to read Json String
This might help,
You already have ArrayList containing required claims as,
ArrayList ARRAY = MY_CLAIMS.get("DATI", ArrayList.class);
To get a JSON string of claims included in this ArrayList, try below code.
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, ARRAY);
byte[] data = out.toByteArray();
String str = new String(data);
str contains properly formatted JSON string (with quotation marks).
i have a JSON:
String jsonString = "{"Tech":"{id :[""],techInside :["Java","C++"]}","id1":"","state":""}";
So i need the value of techInside. How do i access that > I have tried:
JSONObject obj = new JSONObject(jsonString);
string techInside = obj.getJSONObject("Tech").getJSONArray("techInside");
But it gave me an exception:org.json.JSONException: Expected a ',' or '}' at 17.Tried Many other ways but spent a lot of time on it. Need some suggestions please.
Note: i am using escape characters in the string.So please ignore about the escaping characters in the jsonString
Your JSON is invalid. There should be no "" around objects ({}).
Try with this JSON-String:
String jsonString = "{\"Tech\":{\"id\":[\"\"], \"techInside\":[\"Java\", \"C++\"]}, \"id1\":\"\", \"state\":\"\"}"
Or without escaping
{"Tech":{"id":[""], "techInside":["Java", "C++"]}, "id1":"", "state":""}
I think the kind of json you are looking for is
{"Tech": {"id" : "", "techInside" : ["Java","C++"]},"id1":"","state":""}
Not sure, what your requirement is.
Am using jsonobject and json array and converting the final result to string using jsonobject.toString() function and returning the string to browser.
Code snippet:
JSONArray VMs= new JSONArray();
JSONObject resultSet = new JSONObject();
for(Vector<String> stages : mrs)
{
VMs.put(new JSONObject().put("Vm",stages.get(0)));
}
resultSet.append("ServerDetails",(new JSONObject().put("Server",sName).append("Vms", stageNames)));
return resultSet.toString();
output on browser:
"{\"ServerDetails\":[{\"Server\":\"myserver45\",\"Vms\":[[{\"Vm\":\"vm1022\"},{\"Vm\":\"vm9875\"}]]}]}"
I don't want it to return this way. How do i make this return as follows without slashes-
"{"ServerDetails":[{"Server":"myserver45","Vms":[[{"Vm":"vm1022"},{"Vm":"vm9875"}]]}]}"
I don't understand why " gets replaced with \" everywhere. Please help.
If you are using net.sf.json json library, both jsonObject and jsonObject.toString() provide output values without string escape character. Which library you are using..?
Also try returning the original jsonObject itself than the one converted with toString. It might give you the desired result.
Alternate option would be to unescape the string which is send to browser. You can use stringescapeutils from org.apache.commons.lang for this return StringEscapeUtils.unescapeJava(resultSet.toString()) ;
I am stuck in a situation, where my JSONString (ruleFormJSONString) looks like :
{
"ruleDescription":"Test Rule2 Description",
"urlId":"1",
"listOfBusinessdays":["1","2","5","6","7"],
"status":"1",
"hierarchyId":"3",
"fromTime":"08:00",
"toTime":"18:00",
"dcnid":"1",
"eventId":"1",
"rowstate":"1",
"listOfLocations":["ASM","DEL"],
"ruleName":"Test Rule2",
"ruleId":"7","msgId":"1"
}
As you can see there are 2 attributes named fromTime and toTime which has a :
So while parsing this in Java, I used
JSONObject ruleFormJSON = JSONObject.fromString(ruleFormJSONString);
String fromTime = (String)ruleFormJSON.getString("fromTime");
String toTime = (String)ruleFormJSON.getString("toTime");
I am getting a NumberFormatException which is
java.lang.NumberFormatException: For input string: "18:00"
So please suggest me how, to get the value in the corresponding String variable.
Any help will be appreciated.
It seems there is an error on this line:
"listOfBusinessdays":"1","2","5","6","7"],
A closed bracket square but no open bracket before.
May be this hang up the parser.