Exception while parsing JSON - java

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.

Related

Android - decode unicode characters without StringEscapeUtils?

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);

Having problems replacing a string...to what i want

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);

Using Json with java returns string with \" instead of "

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()) ;

Parsing a JSON Object in Java having special characters

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.

parse json with forward slash

How should I parse this json?
{"label":"KLM/AirFrance"}
I try
jsonObject.getString("label")
But have got an error:
at org.json.JSON.typeMismatch
Any ideas? Thanks.
Code:
ArrayList<Gate> gates = new ArrayList<Gate>();
JSONArray jGates = object.getJSONArray("gates_info");
int gatesLength = jGates.length();
for (int i=0; i<gatesLength; i++) {
Gate gate = new Gate();
JSONObject jGate = jGates.getJSONObject(i);
gate.setId(jGate.getInt("id"));
gate.setLabel(jGate.getString("label"));
gate.setCurrency_code(jGate.getString("currency_code"));
gates.add(gate);
}
Part of response:
"gates_info":[{"id":48,"label":"KLM/AirFrance","payment_methods":
["card"],"currency_code":"usd","is_airline":true},
{"id":1,"label":"Nabortu","payment_methods":
["bank","yandex_money","web_money","terminal","card","svyaznoy","euroset"],
"currency_code":"rub","is_airline":false},
{"id":3,"label":"anywayanyday.com","payment_methods":
["card","euroset","svyaznoy"],"currency_code":"rub","is_airline":false},
{"id":7,"label":"Ozon.travel","payment_methods":
["cash","yandex_money","web_money","terminal","card","elexnet","contact","euroset"],
"currency_code":"rub","is_airline":false},
{"id":8,"label":"tickets.ru","payment_methods":
["card","web_money"],"currency_code":"rub","is_airline":false}
Try to escape forward slash, i.e. write \\/.
The back slash is written twice to escape itself, i.e. to make interpreter to treat it as a "real" back slash.
I have not tried this myself with JSON but typically such problems are solved using this kind of solutions.
Here I had this problem (it nothing to do with escape characters though. You just need to know how to use Json. You need to use the addProperty function: Here is an example you should be able to copy this and get it.
JsonObject temp = new JsonObject();
temp.addProperty(tagName,stringData);

Categories