parse JSON response and add it into List - android

I've got problem with parsing JSON. I've got response from webservice like this :
{
   "data": {
      "1": [
         {
            "id": "2",
            "name": "Szelki bezpieczeństwa",
            "quantity": "1",
            "note": null,
            "picture_id": null,
            "code": "CCCCCCCCCCCCCC"
         },
         {
            "id": "3",
            "name": "Kalosze do brodzenia, wysokie lub biodrowe",
            "quantity": "2",
            "note": "Do wymiany",
            "picture_id": null,
            "code": "DDDDDDDDDDDDDD"
         }
      ],
      "2": [
         {
            "id": "1",
            "name": "Spodnie dla pilarza z ochroną przed przecięciem, klasa min. 1 (wg PN-EN 381-5)",
            "quantity": "2",
            "note": "Uszkodzone",
            "picture_id": null,
            "code": "DAAD086F690E1C36"
         }
      ]
   }
}
I try to parse it into PART object and add it to List but somewhere I'm making mistake because object is not being parsed.
public void onResponse(String response) {
Log.e(TAG, "onResponse WHOLE: " + response);
try {
JSONObject responseJSONObject = new JSONObject(response);
String arrayString = responseJSONObject.getJSONArray("data").toString();
JSONArray responseJSONArray = new JSONArray(arrayString);
Part tempCarEquipment;
int index = 1;
for (int i = 0; i < responseJSONArray.length(); i++,index++) {
JSONObject object = responseJSONArray.getJSONObject(index);
JSONArray response2 = object.getJSONArray(Integer.toString(index));
String id = object.getJSONObject(Integer.toString(i)).getString("id");
String name= object.getJSONObject(Integer.toString(i)).getString("name");
String quantity= object.getJSONObject(Integer.toString(i)).getString("quantity");
String picture_id= object.getJSONObject(Integer.toString(i)).getString("picture_id");
String code= object.getJSONObject(Integer.toString(i)).getString("code");
tempCarEquipment = new Part(name,quantity,"",picture_id,code,id,"",0);
wholeList.add(tempCarEquipment);
Log.e(TAG, "wholeList: " + wholeList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in advance fo every help! :)

JSON Parsing
You have to use the iterator for this kind of response
basic example of iterator is in this link.

You are trying to parse map as an array here:
String arrayString = responseJSONObject.getJSONArray("data").toString();
Try something like this instead:
List<JSONArray> objects = new ArrayList<>();
Iterator<String> keys = responseJSONObject.getJSONObject("data").keys();
while(keys.hasNext()) {
objects.add(responseJSONObject.getJSONObject("data").get(keys.next());
}
// rest of your stuff
Alternatively, consider using GSON to parse JSON responses using POJOs.

Related

Parse multiple JSON objects in Android

i'm confused on how to parse this JSON.
So far this is my approach. Also please tell me the right approach for parsing JSON in Android
JSON:
{
"latitude":37.8267,
"longitude":-122.423,
"timezone":"America/Los_Angeles",
"offset":-7,
"currently":{
"time":1443322196,
"summary":"Partly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":13,
"nearestStormBearing":77,
"precipIntensity":0,
"precipProbability":0,
"temperature":63.94,
"apparentTemperature":63.94,
"dewPoint":55.46,
"humidity":0.74,
"windSpeed":8.59,
"windBearing":277,
"visibility":8.51,
"cloudCover":0.44,
"pressure":1010.39,
"ozone":261.48
},
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
}
Now the "currently" object is being parsed but when i try to parse "minutely" object it shows no value in Logcat
Here's my code:
JSONObject forecast = new JSONObject(jsonData);
JSONArray summary = new JSONArray(jsonData);
String timezone = forecast.getString("timezone");
String city = getLocationName(forecast.getDouble("latitude"), forecast.getDouble("longitude"));
JSONObject currently = forecast.getJSONObject("currently");
JSONArray hour = summary.getJSONArray("minutely");
for (int i = 0; i < hour.length(); i++) {
JSONObject jsonObject = hour.getJSONObject(i);
String summary = jsonObject.getString("summary");
}
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setTemp(currently.getDouble("temperature"));
currentWeather.setTimezone(timezone);
currentWeather.setLocation(city);
Based on the response from the endpoint url that you added in comments the parsing would look like this
JSONObject forecast = new JSONObject(jsonData);
double latitude = forecast.getDouble("latitude");
double longitude= forecast.getDouble("longitude");
String timezone = forecast.getString("timezone");
JSONObject jsonObjCurrently= forecast.getJSONObject("currently");
//parse string, long and double objects within jsonObjCurrently accordingly
JSONObject jsonObjMinutely= forecast.getJSONObject("minutely");
String summary= jsonObjMinutely.getString("summary");
String icon= jsonObjMinutely.getString("icon");
JSONArray jsonArrayMinutelyData = jsonObjMinutely.getJSONArray("data");
for(int i=0; i<jsonArrayMinutelyData .length(); i++){
JSONObject tempData = jsonArrayMinutelyData.get(i);
long time = tempData.getLong("time");
//parse the remaining object pairs.
}
JSONObject jsonObjHourly= forecast.getJSONObject("hourly");
//similar to minutely parsing. Only has more and different data
JSONObject jsonObjDaily= forecast.getJSONObject("daily");
//similar to hourly parsing.
JSONObject jsonObjFlags= forecast.getJSONObject("flags");
//It has 5 array and 1 string object so parse accordingly.
I have added the parsing logic please save the data accordingly and use it.
You may parse the minutely at wrong path. see code below (tested).
try {
// jsonString from https://api.forecast.io/forecast/8162461ea194cb97c80209d6edf4df94/37.8267,-122.423
String jsonString = "";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject minutely = jsonObject.getJSONObject("minutely");
Log.d("JSON", "minutely: " + minutely);
String summary = minutely.getString("summary");
Log.d("JSON", "summary: " + summary);
JSONArray datas = minutely.getJSONArray("data");
for (int i = 0; i < datas.length(); i++) {
JSONObject data = datas.getJSONObject(i);
Log.d("JSON", "data # index" + i + ": " + data);
}
} catch (JSONException e) {
e.printStackTrace();
}
output:
D/JSON ( 1590): minutely: {"summary":"Partly cloudy for the hour.","icon":"partly-cloudy-night","data":....
D/JSON ( 1590): summary: Partly cloudy for the hour.
D/JSON ( 1590): data # index0: {"time":1443331140,"precipIntensity":0,"precipProbability":0}
D/JSON ( 1590): data # index1: {"time":1443331200,"precipIntensity":0,"precipProbability":0}
....
This is not a valid json.
You can check your logcat for the exception thrown.
If the exception has been caught, try and print stack trace. That will help you know where the problem is.
i check your json again and it should be one of two cases
the first is like
{
"latitude":37.8267,
"longitude":-122.423,
"timezone":"America/Los_Angeles",
"offset":-7,
"currently":{
"time":1443322196,
"summary":"Partly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":13,
"nearestStormBearing":77,
"precipIntensity":0,
"precipProbability":0,
"temperature":63.94,
"apparentTemperature":63.94,
"dewPoint":55.46,
"humidity":0.74,
"windSpeed":8.59,
"windBearing":277,
"visibility":8.51,
"cloudCover":0.44,
"pressure":1010.39,
"ozone":261.48
},
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
}
and the solution will be look like.
JSONObject minutely = forecast.getJSONObject("minutely");
second it like
[
{
"latitude": 37.8267,
"longitude": -122.423,
"timezone": "America/Los_Angeles",
"offset": -7,
"currently": {
"time": 1443322196,
"summary": "Partly Cloudy",
"icon": "partly-cloudy-night",
"nearestStormDistance": 13,
"nearestStormBearing": 77,
"precipIntensity": 0,
"precipProbability": 0,
"temperature": 63.94,
"apparentTemperature": 63.94,
"dewPoint": 55.46,
"humidity": 0.74,
"windSpeed": 8.59,
"windBearing": 277,
"visibility": 8.51,
"cloudCover": 0.44,
"pressure": 1010.39,
"ozone": 261.48
},
"minutely": {
"summary": "Partly cloudy for the hour.",
"icon": "partly-cloudy-night",
"data": [
{
"time": 1443322140,
"precipIntensity": 0,
"precipProbability": 0
}
]
}
}
]
and solution will be that you should change your forecast object to be JsonArray.
You can test the validation of your json here
Minutely is not JSONArray its JSONObject.
Try this:-
JSONObject forecast = new JSONObject(jsonData);
JSONObject jsonObjMinutely= forecast.getJSONObject("minutely");
String summary = jsonObjMinutely.getString("summary");
Your minutely is invalid JSON..
Let's take a look at that closer:
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
},
It doesn't have a closing bracket for both the minutely's JSONObject and data's JSONArray. Also, it has a comma where "data" array actually contains one element.
Fixing those to:
"minutely":{
"summary":"Partly cloudy for the hour.",
"icon":"partly-cloudy-night",
"data":[
{
"time":1443322140,
"precipIntensity":0,
"precipProbability":0
} ]
}
Then your "minutely" object is now valid. This is first.
Then to get your "minutely"
...
JSONObject forecast = new JSONObject(jsonData);
JSONObject minutely = forecast.getJSONObject("minutely");
parsing json is very easy now with android studio. In android studio install plugin GSON then create model class and enter 'alt+insert' it will popup for generator then select GSONFormat and paste your json there you will get model class for your json. In activity where you get json response do this
Gson gson = new Gson();
YourModelClass object = gson.fromJson(jsonResponseObject.toString(), YourModelClass.class);
Here you succefully parsed json. Now its time to use your model class to get data whereever you want it
Please edit your code like below
JSONObject currently = forecast.getJSONObject("currently");
Double humidity = currently.getDouble("humidity");
Long time = currently.getLong("time");
String icon = currently.getString("icon");
Double precipChance = currently.getDouble("precipProbability");
Double temp = currently.getDouble("temperature");
String timezone = forecast.getString("timezone");
JSONObject minutely = forecast.getJSONObject("minutely");
Have a look at below link for complete example of Json Parsing
https://www.dropbox.com/s/q6cjifccbbw9nl1/JsonParsing.zip?dl=0

is my JSON response correct? and why i see this exception when i try to retrieve it?

my problem is that i have an asp. web service .. and it gives me the following result when i invoke it :
[
{
"_OrderDetails": [
{
"ProductName": "FUCHS SUPER GT SAE 10W30 6X5 / FP10100010102",
"TotalAfterDiscount_Lc": "7500",
"MeasureUnitName": "كرتونة",
"TotalPrice_Lc": "7500",
"PricePerUnit_Lc": "75",
"Quantity": "100"
}
],
"Id": "274",
"OrderDate": "4/10/2014 12:00:00 AM",
"Number": "16",
"CustomerName": "الأسد",
"Note": ""
}
]
and in the main activity i do the following :
Gson gson = new Gson();
Log.e("Response", responseJSON);
if (responseJSON != null) {
try {
JSONObject jsonObj = new JSONObject(responseJSON);
//JSONArray jsonarr =new JSONArray();
// details=jsonObj.getJSONObject(0);
// Getting JSON Array node
details = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String product = c.getString(TAG_PRODUCT);
Log.e("prodeuct",product+"");
}
i see the response in the logcat correctly but when i try to get any object from the array i see a JSON exception it says :
JSON array can't be converted to JSON object !!!
please can anyone help me??
Because your json return jsonarray and you are try to access jsonobject.
Change your code:
if (responseJSON != null) {
try {
JSONArray jsonObj = new JSONArray(responseJSON);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
// your code
}
Chang to JSONArray
if (responseJSON != null) {
try {
JSONArray array = new JSONArray(responseJSON)
}
http://jsonviewer.stack.hu/ use it to view your json and resolve it accordingly. you are using json array as json object.
use these:
JSONObject jsonObj = new JSONObject(responseJSON);
to
JSONArray jr = new JSONArray(responseJSON);

JSON Handling Quick

Hey guys this is the first time I am doing JSON and I have gotten the json from the server. Now my only question is how do I take the data.
The JSON includes
[
{
"name": "Joe Smith",
"employeeId":1,
"company": "ABC",
"phone": {
"work": "555-555-5555",
"home": "666-666-6666",
"mobile": "777-777-7777"
}
},
{
"name": "Does Smith",
"employeeId":2,
"company": "XYZ",
"phone": {
"work": "111-111-1111",
"home": "222-222-2222",
"mobile": "333-333-3333"
}
}
]
jsonData is my string of the JSON
Currently I have:
JSONObject json = new JSONOBject(jsonData);
JSONObject data = json.getJSONObject(*******)
JSONArray phones = data.getJSONArray("phone");
not sure what to put on the second line. Also, what is the best way to group the information.
Please make it easy to understand, not exactly a professional yet haha
Thanks!
Your first line is wrong because current string is JSONArray of JSONObject's so get data from current string as:
JSONArray json = new JSONArray(jsonData);
for(int i=0;i<json.length();i++){
JSONObject data = json.getJSONObject(i);
// get name,employeeId,... from data
String str_name=data.optString("work");
//...
JSONObject jsonobjphones = data.getJSONObject("phone");
// get work from phone JSONObject
String str_work=jsonobjphones.optString("work");
//....
}
Try this
List list=new ArrayList();
JSONObject jObject = new JSONObject(str_response_starter);
JSONArray json_array_item_id = jObject.getJSONArray("itemid");
System.out.println("json array item id"+json_array_item_id);
JSONArray json_array_item_name = jObject.getJSONArray("itemname");
System.out.println("json array item name"+json_array_item_name);
JSONArray json_array_item_type = jObject.getJSONArray("type");
System.out.println("json array item type"+json_array_item_type);
JSONArray json_array_item_cost = jObject.getJSONArray("cost");
System.out.println("json array item cost"+json_array_item_cost);
Now
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
String k, v;
Iterator<String> itKeys = kvPairs.keySet().iterator();
while (itKeys.hasNext()) {
k = itKeys.next();
System.out.println(" value of k"+k);
v = kvPairs.get(k);
System.out.println(" value of v"+v);
In JSON, [] represents JSONArray, {} represents JSONObject. In your JSON string, it starts with [, so you need to start with JSONArray:
JSONArray people = new JSONArray(jsonData);
And then you'll notice that each person is a JSONObject, so now you need to loop them in order to get their information:
for(int i=0;i<people.length();i++){
JSONObject person = people.getJSONObject(i);
JSONObject phones = person.getJSONObject("phone"); //phone is also a JSONObject, because it starts with '{'
String workPhone = phones.get("work");
}

How to get a value from JSON Object by a key?

How to get the value by key in a JSON object? I had used following code but it receives "org.json.JSONException". Advance thanks for any help.
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jObject = new JSONObject(resultJSON);
JSONObject jsonObject = jObject.getJSONObject("Data");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jsonObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jsonObject.getString(key);
map.put(key,value);
Log.d("Key Value","key: "+key+" Value: "+value);
}
Logcat details
org.json.JSONException: Value [{"AreaID":"13","Phone":"654321","RegionName":"Sivakasi"},{"AreaID":"14","Phone":"12345","RegionName":"ANJAC"}] at Data of type org.json.JSONArray cannot be converted to JSONObject
The structure of your JSON is wrong, you should use a Key for the second JSONObject , like this:
{
Data: {
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
\"KEY\": {
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
}
Or the DATA should be a JSONArray ( surrounded by [] ) like this :
{
Data: [
{
\"AreaID\": \"13\",
\"Phone\": \"654321\",
\"RegionName\": \"Sivakasi\"
},
{
\"AreaID\": \"14\",
\"Phone\": \"12345\",
\"RegionName\": \"ANJAC\"
}
]
}
NOTE : you can check if your json is valid or not here
Personnaly , i prefer the second way ( Using JSONArray) , because the data inside has the same attributes (AreaID, Phone, REgionName). To parse data in this case , your code should be someting like this :
String resultJSON = "{Data:[{\"AreaID\":\"13\", \"Phone\":\"654321\", \"RegionName\":\"Sivakasi\"}, {\"AreaID\":\"14\", \"Phone\":\"12345\", \"RegionName\":\"ANJAC\"}]}";
JSONObject jsonRoot = new JSONObject(resultJSON);
JSONArray jsonData = jsonRoot.getJSONArray("Data");
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonOBject = jsonData.getJSONObject(i);
Log.d(TAG, "json ("+i+") = "+jsonOBject.toString());
// do what you want with your JSONObject , i.e :add it to an ArrayList of paresed result
String areaID = jsonOBject.getString("AreaID");
int phoneNumber = jsonOBject.getInt("Phone");
String regionName = jsonOBject.getString("RegionName");
}
This is invalid JSON format. Before you convert your string to JSON object format, be sure about it's valid or not.
Please check validity of your JSON.
Hope it may help.

Parsing JSON object in android

I have JSON object as follows:
[
{
"Project": {
"id": "1",
"project_name": "name"
},
"AllocationDetail": [
{
"id": "1",
"project_id": "1",
"team_name": "ror",
"week_percentage_work": "50",
"in_today": "1",
"actual_hours": "30",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:48:33",
"modified": "2012-01-13 15:48:33"
},
{
"id": "2",
"project_id": "1",
"team_name": "php",
"week_percentage_work": "40",
"in_today": "2",
"actual_hours": "50",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:49:40",
"modified": "2012-01-13 15:49:40"
}
]
}
]
I want to parse data in android and store it into DB, but i m getting confused in Jsonobject
thanks
the best JSON Tutorial i have seen, I leared json parsing from this tutorial, hope it will help
The following is a snippet code for parsing your json string. Kindly go through it:
String response = <Your JSON String>;
String Project = null;
String AllocationDetail = null;
try {
JSONArray menuObject = new JSONArray(response);
for (int i = 0; i< menuObject.length(); i++) {
Project = menuObject.getJSONObject(i).getString("Project").toString();
System.out.println("Project="+Project);
AllocationDetail = menuObject.getJSONObject(i).getString("AllocationDetail").toString();
System.out.println("AllocationDetail="+AllocationDetail);
}
JSONObject jsonObject = new JSONObject(Project);
String id = jsonObject.getString("id");
System.out.println("id="+id);
String project_name = jsonObject.getString("project_name");
System.out.println("project_name="+project_name);
JSONArray jArray = new JSONArray(AllocationDetail);
for (int i = 0; i< jArray.length(); i++) {
String team_name = jArray.getJSONObject(i).getString("team_name").toString();
System.out.println("team_name="+team_name);
String week_percentage_work = jArray.getJSONObject(i).getString("week_percentage_work").toString();
System.out.println("week_percentage_work="+week_percentage_work);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There are two ways for parsing JSON
Google GSON
JSON
When your content of JSON is too complex and long enough you can prefer usin GSON its much easier to maintain than JSON parsing each value manually.
Use jsonlint.com to read your json better. It appears that the json that you have copied here is invalid.
String response = <Your JSON String>; // add your Json String here
response = response.replace("[","").replace("]",""); // Just remove all square braces
JSONObject json = new JSONObject(response); //Convert the Json into Json Object
JSONObject jProject = json.getJSONObject("Project"); // get your project object
String project_id = jProject.getString("id"); // Get the value of Id
String project_name = jProject.getString("project_name"); // get the value of Project_name
The above code can be use many times as you want to parse the Json.
I know its too late, but It may help many people who are trying to find the same answer.
I was trying to find the same solution, but it was too hard to use the Accepted answer because of too many lines of codes, But I got the same results with hardly few lines of codes.

Categories

Resources