Android: Parsing JSONArray of a JSONObject but still get syntax Error - java

i've read alot about parsing json in android and i don't know where i missed because i thinks that i do it right but it's keep showing me error
Here is my JSON:
{
"categories": [
{
"id": 1,
"category_name": "Kiehn, Kohler and Russel",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
},
{
"id": 2,
"category_name": "Flatley PLC",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
}]
}
And here is my handle in android
try {
ArrayList<TagModel> tagdata = new ArrayList<>();
JSONObject object = new JSONObject(response);
//Category
ArrayList<CategoryModel> catedata = new ArrayList<>();
JSONArray catearray = object.getJSONArray("categories");
for (int i = 0; i < catearray.length(); i++) {
JSONObject product = catearray.getJSONObject(i);
CategoryModel recommend_model = new CategoryModel();
recommend_model.setCategoryName(product.getString("category_name"));
recommend_model.setCategoryId(String.valueOf(product.getInt("id")));
catedata.add(recommend_model);
}
} catch (JSONException e) {
e.printStackTrace();
}
The Error keep telling the same issue that is:
at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
at org.json.JSONTokener.readObject(JSONTokener.java:393)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONObject.(JSONObject.java:159)
at org.json.JSONObject.(JSONObject.java:176)
at kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:44)
08-30 06:47:37.283 22712-22712/kh.com.example.sopheak_pc.CenturyRecipe
W/System.err: at
kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:38)
Here is the full log message:
and when i debug, the error start from
JSONObject object = new JSONObject(response);
and it's going to
catch (JSONException e) {
e.printStackTrace();
}
Sorry if it's a bit messy because i want to show everywhere that relate to the error Thanks you!!!
i've just found my error inside string json and here what it's look like

As #Andreas and #Sam Littlefair mention is my json contain "," inside the string so i clean up my data and enter simple data and it's working fine now! Thanks you 2 of you!

Related

Not sure why it has to say not valid Json after replacing the values of paymentKey and Session key

I am trying to read a json file and after traversing to attrib`s called "paymentKey" and "Session key" and changing their values through JSONObject , the post operation failing.
When i checked the out json after performing above changes it seems that structure is bit unordered , changed and even got to learn that json is not an valid one.
This is bit annoying and not sure how to keep the json format in tag after replacing the attrib`s values.
Below is the Json used
{
"idempotentId": "133215472229",
"customerId": "12345",
"brandId": "ANCHOR",
"sellingChannel": "WEBOA",
"items": [
{
"lineItemId": 123,
"productId": "ANCHOR-WEBOA-640213214",
"price": 1.19,
"quantity": 1,
"modifierGroups": [],
"childItems": [],
"note": " Drink without snacks"
}
],
"fulfillment": {
"email": "12#gmail.com",
"phoneNumber": "+912222621",
"fulfillmentType": "PickUp",
"asap": true,
"pickupFirstName": "Kiran",
"pickupLastName": "Kumar",
"locationId": "33211111"
},
"payment": {
"paymentKey": "12222-444-555-2222-44444121e",
"sessionKey": "02f3waAjHJnVCTstOIu0jcSZfm_1HnGum1lZdsu6iDlLxxjO1FYsG9DHz9130ZzMMkjYY9j5w.7V8CijbmiPSo5ESDsq5hsQ.RpYSS5wkgoSSOMjktEyDTHZh1IPq0wNayp--DE3HE53uUgTEehCvHjSsUP5q8U2ZN1kZXbsufwm_mRCV8hLCrmWVTchhVUTJtmEpyYy142DtSp1ikXOVzGN5i9z_oP5e79QvgmU7_n1C5DeARFRagQClT87vUFBUfleSbLaRyH5v3wkU7ji9URUetcq1iAfS5-cNt6-uJaulFJc2y6uNdn0OtjIe74Hp5G7Gx54VYggduoqx5X1rsCssobfUSJUDLt_vVpz5BvhQM88EaysMAB6EcQHoOnZd_YWrz4IDAAZSwSBUFQAkypVmHo5pbvp64cTDrZE73EYkEwJLGf0dRmedMFe2HiU3DiCr97K3I3KuufxYM_eMRIcn739dntxTq4QePtFdqYGWBzXWQutvvqxWQPbNi7PG_-aauEOzlwJiXG94C8t7NGu0SjB8xHf11Z3orf5Ni4-fRKugY8VJNBl39hnb4-d-g47ut7iuiFDkDHJzlSgt9LFq__CxShG_.YkL2w7QEU85VHjpOj5urieCr4-G"
},
"subTotal": 100.19,
"tax": 4.19
}
Below is the snippet of the code
import org.json.JSONObject;
import org.json.JSONArray;
public JSONObject constructCreateOrderPayload( String freedomPayPaymentKey,String orderInit_SessionKey, String payloadFile) {
String filepath = System.getProperty("user.dir")+"/src/test/resources/JsonFiles/"+payloadFile;
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
JSONObject jsonObject = new JSONObject(jsonContents);
JSONObject payment_obj = (JSONObject) jsonObject.get("payment");
payment_obj.put("paymentKey", freedomPayPaymentKey);
payment_obj.put("sessionKey",orderInit_SessionKey);
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println( " After Changes in JSON OBJECT : ");
System.out.println(jsonObject.toString());
System.out.println("");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
payload = jsonObject; // when i print the json boject the format is displaced hence when validated it says invalid json
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
return payload;
}
When I validated the Json after changes it shows as invalid with errors as shown in below snapshot
I tried a lot but no success, can somebody please look in to issue and advise me where I am going wrong or provide an solution this issue.
JSON in unordered, When you print jsonObject before making the changes you will know the order of the JSON is changed, I have used the Jackson Databind libraries and below is a working code, Change it accordingly
String filepath = "C:\\Users\\wilfred\\Desktop\\Input.json";
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(jsonContents);
System.out.println("Before converting : " + expected.toString());
JsonNode payment_obj = (expected.get("payment"));
((ObjectNode) payment_obj).put("paymentKey", "Trial1");
((ObjectNode) payment_obj).put("sessionKey", "Trial2");
System.out.println("After converting : " + expected.toString());
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
}
My approach was correct. The only mistake was i had not supply/pass on the correct values to few of the JSon attributes and that resulted in error response.
Rectified as per requirements and was able to get results correctly, hence closing this.

How to access JSON data with multiple array objects : android

I am stuck in getting the data from the JSON file with multiple data sets.
{
"status": "ok",
"count": 3,
"count_total": 661,
"pages": 133,
"posts": [
{
"id": 20038,
"type": "post",
"slug": "xperia-launcher-download",
"url": "http:\/\/missingtricks.net\/xperia-launcher-download\/",
"status": "publish",
"title": "Download Xperia Launcher app for Android (Latest Version)"
},
{
"id": 94,
"type": "post",
"slug": "top-free-calling-apps-of-2014-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2014-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android November 2014"
},
{
"id": 98,
"type": "post",
"slug": "top-free-calling-apps-of-2016-year",
"url": "http:\/\/missingtricks.net\/top-free-calling-apps-of-2016-year\/",
"status": "publish",
"title": "Best Free Calling Apps for Android December 2016"
}
]
}
I need to access the title, url and status from the above JSON file.
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
} catch (JSONException e) {
Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
I am getting a JSONException with the above code.
What should I do to access the title,status and url from the JSON File?
You have to fetch your JSONArray which is inside a JSONObject , so create a JSONObject and fetch your array with index "posts"
1.) result is a JSONObject so create a JSONObject
2.) Fetch your JSONArray with index value as "posts"
3.) Now simply traverse array objects by fetching it through index
JSONObject jObj = new JSONObject(result);
JSONArray jArray = jObj.getJSONArray("posts");
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.status = json_data.getString("status");
fishData.title = json_data.getString("url");
fishData.sizeName = json_data.getString("title");
data.add(fishData);
}
Note : i don't know weather it is a sample response with shorter version though your json object should ends with } not with , .
[{"id":20038,"type":"post","slug":"xperia-launcher-download","url":"http://missingtricks.net/xperia-launcher-download/","status":"publish","title":"Download
Xperia Launcher app for Android (Latest Version)",
// ^^^ there should be a } not a , to end json
// so make sure to do the correction so it will look like => ...st Version)"},
{"id":94,"type":"post","slug":"top-free-calling-apps-of-2014-year","url":"http://missingtricks.net/top-free-calling-apps-of-2014-year/","status":"publish","title":"Best
Free Calling Apps for Android November 2014", ]
Improvements :
you can use optString to avoid null or non-string value if there is no mapping key
This has two variations
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
fishData.status = json_data.optString("status","N/A");
// will return "N/A" if no key found
or To get empty string if no key found then simply use
fishData.status = json_data.optString("status");
// will return "" if no key found where "" is an empty string
You can validate your JSON here.
If entire JSON getJsonObject() is not working, then you should parse JSON objects & array in multiple arrays then use them.

"No value for" exception for getJSONArray

I have a JSON object like this :
{
"Successful": true,
"Value": {
"Materials":[{
"MaterialID": 37628,
"MaterialID": 0,
"MaterialNo": 26868,
"Type": 0,
"MaterialName": Copper
}],
"Prices": []
}
}
I'm trying to get materials array like this :
public ArrayList<Material> parseMaterial (JSONObject object)
{
try
{
JSONArray materialArray = object.getJSONArray("Materials");
}
catch (JSONException e)
{
Log.d("JSONParser=>parseMaterial", e.getMessage());
}
}
I get this exception :
JSONParser=>parseMaterial﹕ No value for Materials
Can you tell me what is wrong with the code? Thanks.
You're missing a step: change
JSONArray materialArray = object.getJSONArray("Materials");
to
JSONObject value = object.getJSONObject("Value");
JSONArray materialArray = value.getJSONArray("Materials");
getJSONArray does not 'search' the entire object (this could give unpredictable results if you have multiple Materials in the object), only the first level.

Android - How to parse specific values from JSON Array and display Toast

New to Android and Java in general and I'm learning how to make a JSON call. To do so, I'm following this guide: http://mobiforge.com/design-development/consuming-json-services-android-apps
Here's where things get confusing for me. The author of that tutorial wants the reader to call this API: http://ws.geonames.org/findNearByWeatherJSON?lat=37lng=122
Which returns a JSON object in this format:
{
"weatherObservation": {
"clouds":"scattered clouds",
"weatherCondition":"n/a",
"observation":"KCFV 090852Z AUTO 06005KT
10SM SCT090 SCT110 24/20 A3000 RMK AO2
SLP148 T02390200 53002",
"windDirection":60,
"ICAO":"KCFV",
"seaLevelPressure":1014.8,
"elevation":225,
"countryCode":"US",
"lng":-95.56666666666666,
"temperature":"23.9",
"dewPoint":"20",
"windSpeed":"05",
"humidity":78,
"stationName":"Coffeyville, Coffeyville
Municipal Airport",
"datetime":"2012-07-09 08:52:00",
"lat":37.083333333333336
}
}
Pretty straight forward, except that the API is no longer valid/has limits. In order to finish the project I've instead opted to call this API: http://api.openweathermap.org/data/2.5/weather?lat=37.77&lon=-122.419
Which returns the JSON in this format
{
"coord": {
"lon": 139,
"lat": 35
},
"sys": {
"country": "JP",
"sunrise": 1369769524,
"sunset": 1369821049
},
"weather": [
{
"id": 804,
"main": "clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"main": {
"temp": 289.5,
"humidity": 89,
"pressure": 1013,
"temp_min": 287.04,
"temp_max": 292.04
},
"wind": {
"speed": 7.31,
"deg": 187.002
},
"rain": {
"3h": 0
},
"clouds": {
"all": 92
},
"dt": 1369824698,
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
I can make the call just fine, but how do I display the "main" and "description" strings in the "weather" array? More specifically, how do I display this information as a Toast?
Here's what I have:
protected void onPostExecute(String result){
try {
JSONArray weatherArray = new JSONArray(result);
JSONArray wArray = new JSONArray("weather");
String mainWeather = wArray.getString(1);
String mainDescription = wArray.getString(2);
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
BecauseI am following the mobiforge Tutorial, I have not deviated anywhere else except for this particular block of code.
Thanks for the help!
Edit:
There are several solutions here that work see #swats and #user3515851. I have chosen #remees-m-syde due to it's simplicity. Primarily because his solution did not require that I go through the for loop.
I have used optJSONArray or optString, instead of getJSONArray or getString as "opt" will return "" if there is no value for that key.. it will not throw any exception like in case of getString()
Try below code
JSONObject rootJsonObj = new JSONObject(result);
JSONArray wArray = rootJsonObj.optJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject weatherJsonObj = wArray.optJSONObject(i);
String mainWeather = weatherJsonObj.optString("main");
String mainDescription = weatherJsonObj.optString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
Parsing issue was there, You should have taken object from response result.
EDIT: No need of try catch block while using optJSONArray or optString.
You are unable to get the data because there is one json object inside the "weather" JSONArray.
JSONArray starts with - [
JSONObject starts with - {,
So first get the JSONArray and then the JSONObject inside it.
"weather": [ ----Array
{ ----Object
"id": 804,
"main": "clouds",
"description": "overcast clouds",
"icon": "04n"
}
]
You have to get this JSONObject and then get the String from it like the below code showing.
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = weatherArray.getJSONArray("weather");
JSONObject jobj = wArray.getJSONObject(0);
String mainWeather = jobj.getString("main");
String mainDescription = jobj.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
When there is multiple object in Array, Get it as below.
JSONObject rootJsonObj = new JSONObject(result);
JSONArray wArray = rootJsonObj.optJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject weatherJsonObj = wArray.getJSONObject(i);
String mainWeather = weatherJsonObj.getString("main");
String mainDescription = weatherJsonObj.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(String result){
try {
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = weatherArray.getJSONArray("weather");
for(int i=0;i<wArray.length,i++){
JSONObject object=wArray.getJSONObject(i);
String mainWeather=object.getString("main");
String mainDescription=object.getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
I hope this one will help to you :)
I assume you obtained the weather array from parsing this JSON now to retrieve the values from it
JSONObject object=null;
try {
JSONObject object=array.getJSONObject(0);
String main=object.getString("main");
String description=object.getString("description");
} catch (JSONException e) {
e.printStackTrace();
}
and now use the strings in your toast
Assuming result contains the JSON, here is how to get main, and description form weather :
JSONObject resJSON = new JSONObject(result);
JSONArray weatherArray = resJSON.getJSONArray("weather");
for(int i = 0; i < weatherArray.length(); i++) {
JSONObject weatherJSON = weatherArray.getJSONObject(i);
System.out.println(weatherJSON.getString("main"));
System.out.println(weatherJSON.getString("description"));
}
Recently, I found out json2pojo useful tool for json parsing, works with anything Jackson,Gson,Java etc.
Hope this will help you.
Try this
JSONObject weatherObject = new JSONObject(result);
JSONArray wArray = weatherObject.getJSONArray("weather");
for (int i = 0; i < wArray.length(); i++) {
JSONObject wObject = wArray.getJSONObject(i);
if(wObject.has("description")) {
Log.d("TAG", wObject.getString("description"));
}
if(wObject.has("main")) {
Log.d("TAG", wObject.getString("main"));
}
}
Use this
JSONObject weatherArray = new JSONObject(result);
JSONArray wArray = new JSONArray("weather");
String mainWeather = ((JSONObject)wArray.getJSONObject(0)).getString("main");
String mainDescription = ((JSONObject)wArray.getJSONObject(0)).getString("description");
Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();

JSON parsing Issues Redux

I had issues in the past with parsing my JSON code, and I almost had it and lost all my code changes. I am putting here the guts of it getting my JSON (which I have verified it gets fine). It's just the parsing of it...I need to get the "fulltext" field and I guess put it into an array...
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag" , "Error converting result " + e.toString());
}
try{
JSONObject rootobject = new JSONObject(result).getJSONObject("query").getJSONObject("results");
} catch (JSONException e){
Log.e("JSON Parser", Log.getStackTraceString(e));
e.printStackTrace();
}
return null;
Within this, the JSONObject area I believe is incorrect. I need to iterate over all of the JSON objects getting the "fulltext" value from all of them and eventually putting them into the database. I'm drawing the team names from this website.
In my mind, I should be able to use
String teamname = rootobject.getString("fulltext");
in some way. I have tried this, but it doesn't work at all. In fact I get the error message "No value for fulltext" when I check the error logs.
I know I'm going wrong somewhere but can't quite place it. I'm still confused with JSON parsing and whatnot but I'm determined to get there.
This is a link to the sample JSON (the URL that I'm accessing)
http://bit.ly/1JnlSck
My apologies for forgetting this in the first post.
What you probably should do is restructure your JSON. Currently you have it like this...
"results": {
"Team:\"Die Unglaublichen\"": {
"printouts": [],
"fulltext": "Team:\"Die Unglaublichen\"",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
"namespace": 822,
"exists": true
},
"Team:(Can't Stand) Le Kubb Bricks": {
"printouts": [],
"fulltext": "Team:(Can't Stand) Le Kubb Bricks",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
"namespace": 822,
"exists": true
}
}
... where "results" is a JSONObject containing several child JSONObjects. If you can rework it so that "results" is a JSONArray containing JSONObjects, like so...
"results": [
{
"Team": "Die Unglaublichen",
"printouts": [],
"fulltext": "Team:\"Die Unglaublichen\"",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
"namespace": 822,
"exists": true
},
{
"Team": "(Can't Stand) Le Kubb Bricks",
"printouts": [],
"fulltext": "Team:(Can't Stand) Le Kubb Bricks",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
"namespace": 822,
"exists": true
}
]
... then you can loop through the "results" array and get each of its JSONObjects and any name/values you wish:
try {
JSONArray resultsArray = rootObject.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject teamObject = resultsArray.getJSONObject(i);
String fullText = teamObject.getString("fulltext");
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories