Android: Best practice for handling JSON data - android

I've been researching how to query JSON data from a server and parse it for use in my application. However, I've found a number of different ways to do the same thing. I realize there are different JSON parsers out there, so let's assume I'm sticking with the standard one. The main question I have has to do with the server requests. Here is my current code for my MapActivity
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a Progress Dialog
mProgressDialog = new ProgressDialog(MapActivity.this);
mProgressDialog.setTitle("Downloading Data");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Retrieve JSON Objects from the given URL address
jsonarray = JSONFunctions.getJSONfromURL("myurl");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("id", String.valueOf(i));
map.put("name", obj.getString("name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Do something with data
mProgressDialog.dismiss();
}
}
If the structure of my JSON data looks weird, it's because it's stored in an unnamed array so I don't have to create an object first. Anyway... I essentially based this off of this tutorial. However, they have soooo much more code. Is that all really necessary? I didn't think so. I searched around more and found other examples that used half the code and essentially did the same thing. So my question, as a beginning Android programmer, is what is the best practice for handling JSON data? Thanks!
Example of JSON file:
[
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
},
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
}
]

Try this...
private class TestJSONParsing extends AsyncTask<JSONArray, Void, JSONArray>
{
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, String> map;
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(MapActivity.this);
mProgressDialog.setTitle("Downloading Data");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected JSONArray doInBackground(JSONArray... params)
{
return JSONFunctions.getJSONfromURL("myurl");
}
#Override
protected void onPostExecute(JSONArray resultArray)
{
super.onPostExecute(resultArray);
mProgressDialog.dismiss();
if (null != resultArray)
{
int resultLength = resultArray.length();
if (resultLength > 0)
{
try
{
for (int i = 0; i < resultLength; i++)
{
JSONObject jsonObject = resultArray
.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", jsonObject.getString("name"));
arraylist.add(map);
}
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
if (arraylist.size() > 0)
{
SimpleAdapter adapter = new SimpleAdapter(
MapActivity.this, arraylist,
R.layout.your_simple_row, new String[]
{ "id", "name" }, new int[]
{ R.id.nameId, R.id.name });
// bind adapter to your components
listView.setAdapter(adapter);
}
}
} else
{
Toast.makeText(getApplicationContext(), "No data",
Toast.LENGTH_SHORT).show();
}
}
}

#leerob Hello, at one time I found myself in a dilemma where you are, but lately I have used base classes that brings Android to handle json and is pretty good, a good practice I recommend you is to declare constants for the keys of json, I share an example:
public void insertMovieTypeFromJson(String movieTypeJsonStr) throws JSONException {
final String ID = "id";
final String TYPE = "type";
final String DESCRIPTION = "description";
if (movieTypeJsonStr == null)
return;
try {
JSONArray movieTypeArrayJson = new JSONArray(movieTypeJsonStr);
Vector<ContentValues> cVVector = new Vector<>(movieTypeArrayJson.length());
for (int i = 0; i < movieTypeArrayJson.length(); i++) {
long id;
String type;
String description;
JSONObject movie = movieTypeArrayJson.getJSONObject(i);
id = movie.getLong(ID);
type = movie.getString(TYPE);
description = movie.getString(DESCRIPTION);
ContentValues movieTypeValues = new ContentValues();
movieTypeValues.put(MovieContract.MovieTypeEntry._ID, id);
movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_TYPE, type);
movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_DESCRIPTION, description);
cVVector.add(movieTypeValues);
}
int inserted = 0;
if (cVVector.size() > 0) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = getContext().getContentResolver().bulkInsert(MovieContract.MovieTypeEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "MovieTask Complete. " + inserted + " MovieType Inserted");
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
Json:
[
{
"id": "1",
"type": "Action & Adventure",
"description": "Action & Adventure"
},
{
"id": "2",
"type": "Animation",
"description": "Animation"
},
{
"id": "3",
"type": "Comedy",
"description": "Comedy"
},
{
"id": "4",
"type": "Terror",
"description": "Terror"
}
]

Related

issue with JSONArray cannot be converted to JSONObject

hi guys i don't know why but i get this error: JSONArray cannot be converted to JSONObject.
I show you my code!I hope that you can help me! thanks in advance everybody!
Sorry, but i am new to JSON.
MAIN ACTIVITY:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = " http://v1.tvguideapi.com/programs?channels[]=2161&channels[]=2162&start=1484598600&stop=1484605799";
//private static String url = "http://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("programs");
// JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
/* String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");*/
String title=c.getString("title");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
/* contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);*/
contact.put("title",title);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
/* MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});*/
MainActivity.this, contactList,
R.layout.list_item, new String[]{"title"}, new int[]{R.id.title});
lv.setAdapter(adapter);
}
}
}
JSON:
[
{
"id": "18879971",
"start": "2017-01-16 20:20:00",
"stop": "2017-01-16 22:30:00",
"lang": "",
"title": "Il Collegio</td>",
"subtitle": "",
"description": "",
"category": "",
"channel_id": "2162",
"icon": null,
"ts_start": 1484598000,
"ts_stop": 1484605800
},
{
"id": "18879856",
"start": "2017-01-16 20:25:00",
"stop": "2017-01-16 22:40:00",
"lang": "",
"title": "I Bastardi di Pizzofalcone",
"subtitle": "",
"description": "Ep.3 - In un fatiscente condominio di Pizzofalcone viene rinvenuto il cadavere di una camariera. Le indagini della squadra portano al marito della donna, ma per Lojacono il caso si complica ulteriormente.",
"category": "",
"channel_id": "2161",
"icon": null,
"ts_start": 1484598300,
"ts_stop": 1484606400
}
]
You should use you have Json Array.
you have [{ },{}] format Here [] shows JsonArray and {} this is json object.
you can have Json array loop through array and get Json object.
JSONArray contacts = new JSONArray(jsonStr);
Instead of using
JSONObject jsonObj = new JSONObject(jsonStr);
Now you can fetch data
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//Get all required data using c.
String id = c.getString("id");
String name = c.getString("start");
}

How to access Multiple JSONArrays with Listview?

I have two Listview,I am getting two JSONArray from server,I am getting following response
[
[
{
"user_status": "1",
"pooja_name": "Festival Sevas",
"sess_date": "Mon Nov 30 2015",
"session_status": "Completed",
"message": "What ever message you want"
}
],
[
{
"user_status": "1",
"pooja_name": "Pushpalankara Seva",
"sess_date": "Tue Dec 15 2015",
"session_status": "Pending",
"message": "What ever message you want"
}
]
]
I am able to parse both the arrays,but in my both listview it display Pushpalankara Seva,what i am trying is in my first listview i want to display Pushpalankara Seva and in second Festival Sevas
class LoadPoojas extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AboutUsFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String,String>> upcomingdata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(POOJA_LISTING_URL, ServiceHandler.GET);
map = new HashMap<String, String>();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
JSONArray pastarray = jsonObj.getJSONArray(0);
for (int i = 0; i < pastarray.length(); i++) {
JSONObject c = pastarray.getJSONObject(i);
// creating new HashMap
// adding each child node to HashMap key => value
map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME));
}
JSONArray upcoming = jsonObj.getJSONArray(1);
for (int i = 0; i < upcoming.length(); i++) {
JSONObject c = upcoming.getJSONObject(i);
// creating new HashMap
// HashMap<String, String> upcomingmap = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME));
}
data.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
/*if(interestaccept == null || interestaccept.length() == 0){
// Toast.makeText(getApplicationContext(), "No response", Toast.LENGTH_SHORT).show();
noacpt.setText(" No Accepted List ");
}
else
{
noacpt.setVisibility(View.INVISIBLE);
}*/
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterPooja(getActivity(),result);
completedpooja.setAdapter(adapter);
adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result);
notcompletedpooja.setAdapter(adapterupcoming);
adapter.notifyDataSetChanged();
adapterupcoming.notifyDataSetChanged();
completedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
/* upcomingaList = new ArrayList<HashMap<String, String>>();
upcomingaList.addAll(result);
adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result);
notcompletedpooja.setAdapter(adapterupcoming);
adapterupcoming.notifyDataSetChanged();
notcompletedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});*/
}
}
I checked you code and found you did mistake in hashmap with same key in both array(inside both For loop). So it overwrite with latest value as per rules of hashmap.
Solution :
Option 1: Take arraylist of hashmap and create new hashmap each new record.
Option 2: Take arraylist of POJO class.
Edit :
public class UserPOJO {
public String user_status;
public String pooja_name;
public String sess_date;
public String session_status;
public String message;
}
Take arraylist of POJO class like below
public ArrayList<UserPOJO> userPOJOs = new ArrayList<UserPOJO>();
Now insert data in arraylist from JSONArray.

Retrieve json data

I am working on an app which I need to parse jsonarray. I have my json values in base64 and I need to decode strings to retrive data with decode String. Here is my code :
private class DecodeData extends AsyncTask<String, Void, String> {
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String response = params[0];
String keys = "";
String value = "";
String b64Value = "";
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
Iterator<String> it = array.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String)it.next();
value = (String)array.getJSONObject(i).get(keys);
b64Value = Base64.DecodeStrToStr(value);
Log.i("ASYNC TASK VALUE", b64Value);
map.put(keys, b64Value);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map.toString();
}
I get only the first JSONObject and I need to get all JSONObject with all values. I can't use getString(name) because my json can have others keys. What am I doing wrong and why am I getting only the first JSONObject and not the others ?
json type :
[
{
"value": "ZG1WdVpISmxaR2tnTWpVZ1lYWnlhV3c4WW5JZ0x6NEtSMVZaUVU1QklFRk1UQ0JUVkVGUw==",
"date_create": "MjAxNC0wNC0yNSAwMDowMDowMA==",
"picture": "aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNWF2cmlsLmpwZw==",
"link": "",
"title": "MjVhdnJpbA==",
"media": "",
"id_news": "MTA5NjI0",
"id_reference": "",
"type": "",
"id_categorie": "",
"date_event": "MjAxNC0wNC0yNSAwMDowMDowMA==",
"chapo": "",
"auteur": "",
"value_out": "dmVuZHJlZGkgMjUgYXZyaWxHVVlBTkEgQUxMIFNUQVI="
},
{
"value": "YzJGdFpXUnBJREkySUdGMmNtbHNQR0p5SUM4K0NrMUJVbFpKVGlCaGJtUWdSbEpKUlU1RVV3PT0=",
"date_create": "MjAxNC0wNC0yNiAwMDowMDowMA==",
"picture": "aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNmF2cmlsMi5qcGc=",
"link": "",
"title": "MjZhdnJpbA==",
"media": "",
"id_news": "MTA5NjMx",
"id_reference": "",
"type": "",
"id_categorie": "",
"date_event": "MjAxNC0wNC0yNiAwMDowMDowMA==",
"chapo": "",
"auteur": "",
"value_out": "c2FtZWRpIDI2IGF2cmlsTUFSVklOIGFuZCBGUklFTkRT"
},
Here is what i am getting with my code :
RESPONSE :{date_create=MjAxNC0wNS0yNSAwMDowMDowMA==, link=, date_event=MjAxNC0wNS0yNSAwMDowMDowMA==, type=, value_out=ZGltYW5jaGUgMjUgbWFpRE9MQSBNSVpJSyBlbiBjb25jZXJ0, picture=aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNW1haS5qcGc=, title=MjUgbWFp, id_reference=, chapo=, value=WkdsdFlXNWphR1VnTWpVZ2JXRnBQR0p5SUM4K0NqeGljaUF2UGdwRVQweEJJRTFKV2tsTElHVnVJR052Ym1ObGNuUT0=, id_news=MTA5NjM0, media=, auteur=, id_categorie=}
Anybody has an idea of how I can do ?
Thank you
Problem:
You are putting all results in the same Map. Each object in the JSONArray will erase the values of previous objects because the keys are the same.
In the end, you get only one value for each key.
Solution:
You need one map per JSON object in the array. You could use a list (or array) of Maps, for instance. Here is some code:
ArrayList<HashMap<String, String>> decodedArray = new ArrayList<>();
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
HashMap<String, String> map = new HashMap<>();
Iterator<String> it = array.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String) it.next();
value = (String) array.getJSONObject(i).get(keys);
b64Value = Base64.DecodeStrToStr(value);
Log.i("ASYNC TASK VALUE", b64Value);
map.put(keys, b64Value);
}
decodedArray.add(map);
}
Add you json value into model object I hope it would be helpful for you.
public class A {
private Vector<B> b = new Vector<B>();
public Vector<B> getB() {
return b;
}
public void addB(B b) {
this.b.add(b);
}
public class B{
private String value;
private String picture;
//add your paramatere here like link, title etc
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
}
Then after parsing value set into bean object like that.
A a = new A();
for (int i = 0; i < jsonArray.length(); i++) {
B b= a.new B();
JSONObject jsonObject= (JSONObject)jsonArray.get(i);
String value= jsonObject.getString("value");
jsonObject.getString("picture");
// get all value from json object set into b object
a.addB(b);
}

JSON Array Not Showing All Values

I'm using JSONParser.java to show JSON data from a url
the url and the data are correct, they show some values of JSON (more than one)
but why this show only one value?
ArrayList<HashMap<String, String>> artikelList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ArtikelURL);
try {
artikels = json.getJSONArray(TAG_ARTIKEL);
for(int i = 0; i < artikels.length(); i++){
JSONObject c = artikels.getJSONObject(i);
// Storing each json item in variable
String tanggal = c.getString(TAG_TGL);
String judul = c.getString(TAG_JUDUL);
String kutipan = c.getString(TAG_KUTIPAN);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TGL, tanggal);
map.put(TAG_JUDUL, judul);
map.put(TAG_KUTIPAN, kutipan);
artikelList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
This is my JSON data:
{
"status":"1",
"total":20,
"artikel":[
{
"tanggal":"2013-08-07",
"judul":"Article One",
"kutipan":"Example of article quote..."
},
{
"tanggal":"2013-07-23",
"judul":"Article Two",
"kutipan":"Example of article quote......"
},
{
"tanggal":"2013-07-22",
"judul":"Article Three",
"kutipan":"Example of article quote......"
},
{
"tanggal":"2013-03-16",
"judul":"Article Four"",
"kutipan":"Example of article quote,..."
}
]
}
Your JSON is invalid, there's an error in your line 22 at 3rd object of your array
"judul":"Article Four"",
Correct JSON is
{
"status": "1",
"total": 20,
"artikel": [
{
"tanggal": "2013-08-07",
"judul": "Article One",
"kutipan": "Example of article quote..."
},
{
"tanggal": "2013-07-23",
"judul": "Article Two",
"kutipan": "Example of article quote......"
},
{
"tanggal": "2013-07-22",
"judul": "Article Three",
"kutipan": "Example of article quote......"
},
{
"tanggal": "2013-03-16",
"judul": "Article Four",
"kutipan": "Exampleofarticlequote,..."
}
]
}
Ok, Now you are getting Network related exception so, solution to this is, you've to use demo code like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new NetworkThread().execute();
}
class NetworkThread extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
ArrayList<HashMap<String, String>> artikelList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ArtikelURL);
try {
JSONArray artikels = json.getJSONArray("artikel");
for(int i = 0; i < artikels.length(); i++){
JSONObject c = artikels.getJSONObject(i);
// Storing each json item in variable
String tanggal = c.getString(TAG_TGL);
String judul = c.getString(TAG_JUDUL);
String kutipan = c.getString(TAG_KUTIPAN);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TGL, tanggal);
map.put(TAG_JUDUL, judul);
map.put(TAG_KUTIPAN, kutipan);
artikelList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Don't forget to add this to AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
Your JSON Is Invalid But assuming you have an outer Json Array for the JsonObject This implementation would work for your nested Json
ArrayList<HashMap<String, String>> artikelList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ArtikelURL);
try {
JSONArray a = json.getJSONArray(TAG_JSON);
for(int i = 0; i < a.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = a.getJSONObject(i);
map.put(TAG_TOTAL, c.getString(TAG_TOTAL));
map.put(TAG_STATUS, c.getString(TAG_STATUS));
artikelList.add(map);
JSONArray akel = e.getJSONArray(artikel);
if(akel != null){
for(int j=0;j<akel.length();j++){
HashMap<String, String> map2 = new HashMap<String, String>();
JSONObject f = akel.getJSONObject(j);
map2.put(TAG_TGL, f.getString(TAG_TGL));
map2.put(TAG_JUDUL, f.getString(TAG_JUDUL));
map2.put(TAG_KUTIPAN, f.getString(TAG_KUTIPAN));
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Android JSON Parsing with multiple arrays

I need to parse JSON file with multiple arrays.
Array is in format:
{
"List": {
"Something": [
{
"Name": "John",
"phone": "test"
}
]
"SomethingElse": [
{
"Name": "Smith",
"phone": "test"
}
]
}
}
Problem is that i don't know what wold be next array name. It is possible to parse data from all arrays without name of it and without changing structure of it?
Thanks.
JSON
{
"data": {
"current_condition": [
{
"cloudcover": "25",
"humidity": "62",
"observation_time": "04:57 PM",
"precipMM": "0.1",
"pressure": "1025",
"temp_C": "10",
"temp_F": "50",
"visibility": "10",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Clear"
}
]
}
]
}
}
TO GET THE VALUE OF "weatherDesc"
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=8mqumbup9fub7bcjtsxbzxx9");
try {
// Locate the array name in JSON
JSONObject on=jsonobject.getJSONObject("data");
jsonarray = on.getJSONArray("current_condition");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
JSONArray sen1=jsonobject.getJSONArray("weatherDesc");
// Retrive JSON Objects
for(int j=0;j<sen1.length();j++){
jsonobject2 = sen1.getJSONObject(j);
map.put("value0", jsonobject2.getString("value"));
map.put("value1",jsonobject2.getString("value"));
map.put("flag", null);
// Set the JSON Objects into the array
arraylist.add(map);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
try this
I had write a function to iterate JsonObject recursively without knowing keys name.
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}
There is a comma missing in your JSON after the Something value, but apart from that, you can parse it using any JSON parser.

Categories

Resources