I managed to get a json response back from a request and i convert it to String lets say:
String response = client.execute(get, handler);
The response looks something like:
"geometry":{"rings":[[[29470.26099999994,40220.076999999583],[29551.560999999754,40324.093000000343],[29597.470999999903,40391.253000000492],[29619.849999999627,40434.842000000179],[29641.708999999799,40471.713999999687],[29701.501000000164,40574.616000000387],[29722.775999999605,40611.230000000447],[29723.673000000417,40613.234999999404]]]}
But I want to have it to look like the following one:
"Coordinates":"29470.26099999994|40220.076999999583,29551.560999999754|40324.093000000343,29597.470999999903|40391.253000000492,45360.235000003|41478.4790000003,45360.2369999997|41478.4729999993,45353.8320000004|41470.7339999992,45372.21|41468.057,45371.8090000004|41467.1390000004"
In summary i want to change the comma between two coordinates in a [ ] set to be separated by pipes"|" instead of comma and to separate a set of two coordinates with , instead of "],["
What i tried:
response = response.replace("],[","\,");
response = response.replace("[[[","\"");
response = response.replace("]]]","\"");
However it does not give me what i wanted...becuz i have no idea to achieve the replace of pipe...tot of using regex but dont know how to. can someone help me please
try something like this
String result = response.replaceAll("([^\\]])(\\,)","$1\\|").replaceAll("[\\[\\]]","");
=> ([^\\]])(\\,) => ([^\])(\,) every comma not preceded by ]
=> [\\[\\]] => [\[\]] every [ or ]
Please note that
replacing using regexp is using String.replaceAll or Pattern class
String are immutable
I think this should work:
String response = "[[[29470.26099999994,40220.076999999583],[29551.560999999754,40324.093000000343],[29597.470999999903,40391.253000000492],[29619.849999999627,40434.842000000179],[29641.708999999799,40471.713999999687],[29701.501000000164,40574.616000000387],[29722.775999999605,40611.230000000447],[29723.673000000417,40613.234999999404]]]";
response = response.replace(",", "|");
response = response.replace("]|[", ",");
response = response.replace("[[[", "\"");
response = response.replace("]]]", "\"");
System.out.println(response);
Related
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.
I am creating a restful api(service) using maven and jersey. My Repository attributeMasterRepository retuns the data in String format.
JSONObject attribute = new JSONObject();
attribute.put("Product_Brand", attributeMasterRepository.getProductBrand(cluster, CouchbaseBucket.RangePlan));
attribute.put("Product_Type", attributeMasterRepository.getProductType(cluster, CouchbaseBucket.RangePlan));
String attributeStr = "[" + attribute.toString() + "]";
return attributeStr;
My above code in the Service layer returns an unexpected "\" on the string.
I need to get rid of the "\".
Here is my Output:
{
"Product_Type":
"[{\"active\":true,\"description\":\"ALL IN ONES\",\"id\":2},
{\"active\":true,\"description\":\"ACCESSORIES\",\"id\":1}]",
"Product_Brand":
"[{\"active\":false,\"brand\":\"101 DALMATIANS\",\"id\":1}]"
}
Could you please let me know on how to get the "\" removed.
Thanks,
IRK
You did not state which libraries you use, but also you can just replace the \ characters:
json.replaceAll("\\\\", "");
Similar questions:
Removing "\" in json object string
JSONObject.toString: how NOT to escape slashes
I am trying to parse through a string which i create after getting a response from an API.
this is the string i am trying to parse:
// API callback
translateText({
"data":{
"translations":[
{
"translatedText": "Ola Mundo",
"detectedSourceLanguage": "en"
}
]
}
}
);
i want to be able to get the Translated text "Ola Mundo", but i don't want to just search through it and get that specific text, as this Text maybe different the next time.
It seems this is a valid JSON object , one option is to convert the string to a JSON object using Jackson library or something else , after that you can get anything you want .
Try to do that with the following Regex:
translatedText": (.*?),
In Java, you approach to the result with:
Pattern p = Pattern.compile("");
Matcher m = p.matcher(str);
If you you remove the translateText(); part and just have:
{ "data":{ "translations":[ { "translatedText": "Ola Mundo",
"detectedSourceLanguage": "en" } ] } }
its a valid JSON object and you can easily use a library to parse it. See this post. This way is recommend if you want to access the data securely.
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()) ;