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);
Related
I have a Signed JWT token and I need to update an existing field, let's call it userName. I'm using NIMBUS + JOSE and. I figured out how to parse it and extract the claims:
SignedJWT.parse(token)
but parsing is not the only thing i need: I have update the field and reassemble its token back. Is there an easy way or any kind of idiomatic solution that will work without recreating the token from scratch.
I spend some time trying to figure out how to modify JWT token using the library.
And I used a quick and dirty solution:
// Split token into parts (parts are separated with '.'
final String[] tokenParts = token.split("\\.");
// decode payload part
final String decodedPayload =
new String(Base64.getDecoder().decode(tokenParts[1]), "UTF-8");
// enrich payload with additional userName field by adding it to the end of
// JSON. Remove the last character which is '}' and append data as String
final String updatedDecodedPayload =
decodedPayload.substring(0, decodedPayload.length() - 1)
+ ",\"userName\":\"" + "Richard" + "\"}";
// update payload with userId field and encode it back to base64
tokenParts[1] = Base64.getEncoder().encodeToString(
updatedDecodedPayload.getBytes()
);
final String updatedToken = String.join(".", tokenParts));
The following code produces a string that has question marks as the display name when I insert an Iranian address(?????, ???????). However if I put the same url into my browser, it returns Tehran, Iran instead of question marks. I know that it has something to do with encoding but how do I get the English text as the browser returns in my java application?
String rawAddress = "Tehran";
String address = URLEncoder.encode(rawAddress, "utf-8");
String geocodeURL = "http://nominatim.openstreetmap.org/search?format=json&limit=1&polygon=0&addressdetails=0&email=myemail#gmail.com&languagecodes=en&q=";
String formattedUrl = geocodeURL + address;
URL theGeocodeUrl = new URL(formattedUrl);
System.out.println("HERE " +theGeocodeUrl.toString());
InputStream is = theGeocodeUrl.openStream();
final ObjectMapper mapper = new ObjectMapper();
final List<Object> dealData = mapper.readValue(is, List.class);
System.out.println(dealData.get(0).toString());
I tried the following code but it produced this: تهران, �ايران‎ for the display name which should be Tehran, Iran.
System.out.println(new String(dealData.get(0).toString().getBytes("UTF-8")));
Use "accept-language" in the URL parameter for Nominatim to specify the preferred language of Nominatim's results, overriding whatever default the HTTP header may set. From the documentation:
accept-language= <browser language string>
Preferred language order for showing search results, overrides the
value specified in the "Accept-Language" HTTP header. Either uses
standard rfc2616 accept-language string or a simple comma separated
list of language codes.
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);
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 having a converting that in to Json with following code
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
FileWriter writer = new FileWriter("myfile.json");
It is working fine and out put is following
[ {"date":"July 4th", "event":"Independence Day"} ]
But I want the following format with a variable assign get value in Json
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
How can i add a variable to that
You can add a new data using put method in JSONObject
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
jsonformatted .put("assign ", "some value")
Edit
OP wants to replace ':' with '='
Well you should not do it , because its the JSON standard.
Attributes and values are assigned using : and not by =
Check this link for more info
JSON wiki