Not able to parse the JSON data - java

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

Related

Deserialize and Filter Nested String in Gson Java

I want to create an Application that can auto-create Memes. Every Meme from the API has different amounts of boxes (fields where the text can sit). Now I want to create an HTTP Request to get the fields for a specific meme ID.
The HTTP Request is working fine but I don't know how to deserialize and filter the received string.
Here is the JSON I want to Deserialize with GSON:
https://api.imgflip.com/get_memes
The solution is:
You need to get a JsonObject then in a JsonElement deserialize the "top-level-elements" and get it as a JsonArray. Then you can Loop through the array and get what you need.
JsonObject jsonObject = new Gson().fromJson(content.toString(), JsonObject.class);
JsonElement entry = jsonObject.getAsJsonObject("data").getAsJsonArray("memes");
JsonArray entryArray = entry.getAsJsonArray();
for (JsonElement element : entryArray) {
JsonObject jsonObjectLoop = element.getAsJsonObject();
if(jsonObjectLoop.get("id").getAsString().equals("14371066")) {
System.out.println(jsonObjectLoop.get("box_count").getAsString());
}
}

String deserialization and conversion to JSON in Java

After deserializing my string and converting it to JSON using the code below:
JSONObject returnValue = new JSONObject();
String toJson = null;
try
{
Object otherObjectValue = SerializationUtils
.deserialize(myBytesArray);
Gson gson = new Gson();
toJson = gson.toJson(otherObjectValue);
returnValue.put(key, toJson);
}
some part of the JSON still has something like:
{ "key":"ATTRIBUTE_LIST", "value":"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"}
which means everything in:
"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"
is one string instead being another object with fields. Is there something I can do to sanitize by JSONObject to make it properly JSON?
The key part is OK, means the whole String is JSON formatted.
For the value part, /shows that the value of value is JSON formatted already.
So you may "deserialize" the value of value again to retrieve an Object result. Or you may ask the creator of origin JSON, to serialize origin Object one time into JSON format.

Unable to get JSON Object in request to the servlet

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.

Restlet throwing error when JSON begins with [

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.

JSONObject in JSONObject

I have an API Output like this:
{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}
I create a simple JSONObject from this API with:
JSONObject json = getJSONfromURL(URL);
After this I can read the data for User like this:
String user = json.getString("user");
But how do I get the Data for stat1 and stat2?
JSONObject provides accessors for a number of different data types, including nested JSONObjects and JSONArrays, using JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).
Given your JSON, you'd need to do something like this:
JSONObject json = getJSONfromURL(URL);
JSONObject user = json.getJSONObject("user");
JSONObject status = user.getJSONObject("status");
int stat1 = status.getInt("stat1");
Note the lack of error handling here: for instance the code assumes the existence of the nested members - you should check for null - and there's no Exception handling.
JSONObject mJsonObject = new JSONObject(response);
JSONObject userJObject = mJsonObject.getJSONObject("user");
JSONObject statusJObject = userJObject.getJSONObject("status");
String stat1 = statusJObject.getInt("stat1");
String stats2 = statusJObject.getInt("stats2");
from your response user and status is Object so for that use getJSONObject and stat1 and stats2 is status object key so for that use getInt() method for getting integer value and use getString() method for getting String value.
To access properties in an JSON you can parse the object using JSON.parse and then acceess the required property like:
var star1 = user.stat1;
Using Google Gson Library...
Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.
// Here I'm getting a status object inside a user object. Because We need two fields in user object itself.
JsonObject statusObject= tireJsonObject.getAsJsonObject("user").getAsJsonObject("status");
// Just checking whether status Object has stat1 or not And Also Handling NullPointerException.
String stat1= statusObject.has("stat1") && !statusObject.get("stat1").isJsonNull() ? statusObject.get("stat1").getAsString(): "";
//
String stat2= statusObject.has("stat2") && !statusObject.get("stat2").isJsonNull() ? statusObject.get("stat2").getAsString(): "";
If You have any doubts , Please let me know in comments ...

Categories