I am getting response with okhttp library android java from a url and i converted that response to string.below is response string :
Here is the response string :
"{\"data\":{\"refrenceCode\":\"upfF+kMKv4Q=\",\"identityTypeId\":\"NV25GlPuOnQ=\",\"idNumber\":\"1000\",\"dateOfBirth\":19961004,\"registrationDate\":\"2020-05-12T12:03:47.647\",\"mobile\":\"0022343 \",\"regionId\":\"NV25GlPuOnQ=\",\"cityId\":\"NV25GlPuOnQ=\",\"carTypeId\":\"NV25GlPuOnQ=\",\"carNumber\":\"aa 000\"},\"status\":true,\"errorCodes\":[]}"
and when i tried to convert that string to json objectwith below method;
JSONObject jsonobj = new JSONObject(responsestring);
I got following json exception :
org.json.JSONException: Value {"data":{"refrenceCode":"upfF+kMKv4Q=","identityTypeId":"NV25GlPuOnQ=","idNumber":"1000","dateOfBirth":19961004,"registrationDate":"2020-05-12T12:03:47.647","mobile":"0022343 ","regionId":"NV25GlPuOnQ=","cityId":"NV25GlPuOnQ=","carTypeId":"NV25GlPuOnQ=","carNumber":"aa 000"},"status":true,"errorCodes":[]} of type java.lang.String cannot be converted to JSONObject
How it can be fixed?
Here is a solution based on the collective work in the comments:
responsestring = responsestring.substring(1, responsestring.length - 1).replace("\\\"", "\"");
Thanks for #chrylis-onstrike- observation, it helped.
I fixed it by removing first and last " and then replacing \ like below
responsestring = responsestring.replace("\","");
Related
I am working on an android project. I need help in this JSON data parsing which I am retrieving from the server:
{"item_name":["Navnita","Navnita","Navnita"],"username":["James","John","Jenny"],"review":["Its a relly nice restaurant for Vegetarians! :)","Cool!","Food is just great!"]}
I just want to populate the RecyclerView with the "username" and his "review".
Right now I am using the following code to parse the JSON data and populate an arrayList which in turn populates the RecyclerView but it gives me error(logcat below):
String result ....;
JSONObject jObject = new JSONObject(result);
JSONArray usernameJsonArray = jObject.getJSONArray("username");
JSONArray reviewJsonArray = jObject.getJSONArray("review");
for(int i=0;i<usernameJsonArray.length();i++){
String username = usernameJsonArray.getJSONObject(i).toString();
String review = reviewJsonArray.getJSONObject(i).toString();
getReviewFeedItemsArrayList.add(new GetReviewFeedItems(username,review));
}
I think that the problem is with this above code but I am not able to figure it out. Here's the logcat:
09-19 14:33:24.295 30572-30646/app.usrete.jayant.delvemitt W/System.err﹕ org.json.JSONException: Value James at 0 of type java.lang.String cannot be converted to JSONObject
09-19 14:33:24.305 30572-30646/app.usrete.jayant.delvemitt W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:100)
09-19 14:33:24.305 30572-30646/app.usrete.jayant.delvemitt W/System.err﹕ at org.json.JSONArray.getJSONObject(JSONArray.java:484)
directly write this in your for loop
String username=usernameJsonArray.getString(i);
Your inner data is not JsonObject its just string
you use the following to code to retrieve the data
JSONObject jObject = new JSONObject(result);
JSONArray usernameJsonArray = jObject.getJSONArray("username");
JSONArray reviewJsonArray = jObject.getJSONArray("review");
for(int i=0;i<usernameJsonArray.length();i++)
{
String username = usernameJsonArray.getString(i);
String review = reviewJsonArray.getString(i);
getReviewFeedItemsArrayList.add(new GetReviewFeedItems(username,review));
}
I think you are getting extra html junks with your echoed JSON format output from the http response.
Just add this after you convert your http response to string. This code will trim off the extra html junks and spit out the json format.
jsonData = jsonData.substring(jsonData.indexOf("{\""), jsonData.lastIndexOf("\"}") + 2);
Here "jsonData" is the String format from your http response.
After this follow the usual steps for JSON Parsing.
I'd use GSON. First convert your JSON into POJO classes, http://www.jsonschema2pojo.org/. Then parse your JSON data with GSON:
Gson gson = new Gson();
PojoClass obj = gson.fromJson(jsonString, PojoClas.class);
I got the following response from the API call :
[{"id":63,"name":"Apple Inc.","ticker":"AAPL","website":"www.apple.com","street1":null,"street2":null,"country":null,"postal_code":null,"city":null,"state":null,"type_value":"PUBLIC","person":[{"id":6854208},{"id":6854192},{"id":7795},{"id":6837866},{"id":6854188},{"id":6840774},{"id":6838278},{"id":7637},{"id":6839671},{"id":6837862},{"id":6840759},{"id":6840766},{"id":6838242},{"id":6840830},{"id":6840838},{"id":7875},{"id":3038662},{"id":865765},{"id":6839669},{"id":6837834},{"id":6839685},{"id":6839931},{"id":6840777},{"id":6838232},{"id":6838260},{"id":1859904},{"id":6854204},{"id":6838238},{"id":6839751}],"type":3001,"revenue":null,"industry":[{"industry":"Computer Hardware","industry_id":5009},{"industry":"Electronics","industry_id":5016},{"industry":"Technology - All","industry_id":5044}],"description":null}]
How do I get the value of name from the response?
This is what I have right now:
System.err.println("fullBspApiUrl"+fullBspApiUrl);
Response resp = get(fullBspApiUrl);
System.err.println("This is response"+resp);
String bJson = resp.asString();
System.err.println("This is response after string conversion"+bJson);
JsonPath jsonpath = new JsonPath(bJson);
System.err.println("Instantiate JsonPath "+jsonpath);
//String bspOrgName = jsonpath.getString("organizationName[0]");
String bspOrgName = jsonpath.getString("organizationName[0]");
System.err.println("This is response after JsonPath string conversion "+bspOrgName);
assertEquals(resp.getStatusCode(),200);
assertEquals(bspOrgName,"Apple Inc");
It returns Null instead of Apple.
get(fullBspApiUrl).then().statusCode(200).
and().assertThat().body(name[0], equalTo("Apple Inc"))
name[0] works fine. The previous response had it as OrganizationName
I have created a JSON object manually using the data obtained in java script and sent the JSON Object to a servlet using Ajax.
The Object is able to receive but unable to convert to JSON Object again. I am using json-simple-1.1.jar .
I tried
JSONObject json=(JSONObject)new JSONParser().parse("json_data");
But ended with the following error
Aug 31, 2015 2:28:13 AM source.main.UpdateDetails doGet
SEVERE: null
Unexpected character (j) at position 0.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at source.main.UpdateDetails.processRequest(UpdateDetails.java:55)
at source.main.UpdateDetails.doGet(UpdateDetails.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
The output of JSON File sent as request is as follows :
{
"0":
{
"card_name":"Pallela.Manga",
"aadhar_eid":"1046106160065750110728131521",
"aadhar_uid":"693228374919",
"relation":"SELF",
"age":"43"
},
"1":
{
"card_name":"KondaBabu",
"aadhar_eid":"1046106160008020110728125714",
"aadhar_uid":"996251988555",
"relation":"HUSBAND",
"age":"47"
},
"2":
{
"card_name":"SrinivasaRao",
"aadhar_eid":"1046106125348220110728131743",
"aadhar_uid":"609986909901",
"relation":"SON","age":"25"
},
"3":
{
"card_name":"Ganesh",
"aadhar_eid":"1046106160002957110728132026",
"aadhar_uid":"603873912563",
"relation":"SON",
"age":"23"
}
}
Please help me out of this.. Thank you
You are passing a literal String to the function, not the actual data:
JSONObject json = (JSONObject) new JSONParser().parse("json_data");
// ^^^^^^^^^^^
it should be:
JSONObject json = (JSONObject) new JSONParser().parse(json_data);
assuming json_data is a variable that contains the String json data
previously I created a JSON String and parsed it to JSON Object using JSON.parse(json_string);
and i've sent the same to the servlet. The servlet trying to read it but as it is got the object as string it is printing as [object object] and while trying to parse back to JSON String giving above mentioned error
finally i got help from stackoverflow from another post related
How to read json sent by ajax in servlet
I made a string out of json using the below and sent to the servlet.
JSON.stringify(JSONobj)
The servlet received the string and created the JSON Object successfully using
JSONObject json = (JSONObject) new JSONParser().parse("json_data");
sorry if my english is bad... Thank you
String json_Data = "{ .....}"; // your json format data
JSONParser parser = new JSONParser();
Object obj = parser.parse(json_Data);
JSONObject jsonObj = (JSONObject)obj;
This works fine please test.
You see only way to get json object from request is by reading lines from buffer reader and appending then to string builder. Then you get full json object request. Then you can parse that json object using getJsonobject or getString. I just implemented the same.
response.setContentType("application/json");
//Gson gson = new Gson();
StringBuilder sb = new StringBuilder();
String s;
while ((s = request.getReader().readLine()) != null) {
sb.append(s);
}
System.out.println(sb.toString());//got the full request as string.
JSONObject requestObj = new JSONObject(sb.toString());
JSONObject reqjson=requestObj.getJSONObject("Request");
JSONObject auJsonObject=reqjson.getJSONObject("Verification");
JSONObject getopobj=reqjson.getJSONObject("GetAllOperators");
String userid=auJsonObject.getString("username");
String pass=auJsonObject.getString("password");
String service_type=getopobj.getString("type");
Then using these values i send some response in json format.
out.println(obj);//obj is my jsonobject for response.
I'm using Restlet to consume a json webservice and I'm getting this error:
A JSONObject text must begin with '{' at character 1
The json response I'm getting begins with a [, which seems to be causing the issue.
Is there a way to work around this?
Here is my code:
ClientResource resource = new ClientResource(
"https://api.prosper.com/api/Listings?$top=3");
resource.setChallengeResponse(
ChallengeScheme.HTTP_BASIC, "username", "password");
Representation representation = resource.get();
JsonRepresentation jsonRepresentation = new JsonRepresentation(representation);
JSONObject jsonObject = jsonRepresentation.getJsonObject();
Json that starts with a [ is a json array. Json that starts with { is a json object.
Use JsonRepresentation#getJsonArray()
JSONArray jsonArray = jsonRepresentation.getJsonArray();
Before you continue, familiarize yourself with the json format.
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()) ;