Converting JSONarray to ArrayList
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
How to convert JSONArray to ArrayList?
Simple example :
List<Model> data = new ArrayList<>();
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
data.add(new Model(/*fill your data*/));
}
Convert Json Array to normal Java list
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
Convert JSONArray to String Array
Take a look at this tutorial.
Also you can parse above json like :
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}
JsonArray to Arraylist Conversion
Internally this JsonArray implements list interface so type casting to List is perfectly fine. Moreover iterating each and every element will access list one by one which will be overhead(Performance impact).
If you need alternate way you can use toCollection static method from the same JsonArray class
How to convert JSONArray to arraylist
The problem is in your JSONParcer
class. In the code below, you are trying to create a JSON Object from a JSON Array (json
) that's why you are getting the error type org.json.JSONArray cannot be converted to JSONObject
.
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON parcer" , "Error parcing data " +e.toString());
}
A fix for this would be to remove that part of your code since you are reading json
twice.
You are already doing it correctly here --> JSONArray jsonArray = new JSONArray(json);
.
public class JSONParcer {
ArrayList<Person> getArrayOfWebData = new ArrayList<Person>();
static InputStream is = null;
static JSONArray jsonArray = null;
static String json = "";
....
// change getJSONFromUrl to return ArrayList<Person>
public ArrayList<Person> getJSONFromUrl(String url) {
//делаем HTTP запрос
....
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (IOException e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try{
jsonArray = new JSONArray(json);
for (int i=0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
Person resultRow = new Person();
resultRow.cardID = json_data.getString("ID");
resultRow.cardName = json_data.getString("CardName");
resultRow.cardCode = json_data.getString("CardCode");
resultRow.cardCodeType = json_data.getString("CardCodeType");
resultRow.cardHolderName = json_data.getString("CardHolderName");
resultRow.cardCountryCode =json_data.getString("CardCountryCode");
resultRow.cardHolderID = json_data.getString("CardHolderID");
resultRow.cardSumRait = json_data.getString("CardSumRait");
resultRow.votesCount = json_data.getString("VotesCount");
resultRow.rating = json_data.getString("Rating");
getArrayOfWebData.add(resultRow);
}
} catch (JSONException e) {
e.printStackTrace();
}
// return ArrayList<Person>
return getArrayOfWebData;
}
Then in your MainActivity
, change the object returned by doInBackground
, the object input type to AsyncTask
and the object input type to onPostExecute
to JSONArray
:
public class MainActivity extends ActionBarActivity {
...
public class JsonParce extends AsyncTask<String, String, ArrayList<Person>>{
@Override
protected ArrayList<Person> doInBackground(String... args) {
JSONParcer jsonParcer = new JSONParcer();
ArrayList<Person> personArrayList = jsonParcer.getJSONFromUrl(url1);
return personArrayList;
}
@Override
protected void onPostExecute(ArrayList<Person> personArrayList) {
int a = personArrayList.size();
for(int i =0 ; i<a ; i++){
Log.i("WORKS", personArrayList.get(i).toString());
}
}
}
}
EDIT
I updated my answer, based on your comment. Your JsonParce
AsyncTask
now returns an ArrayList
of Person
s. Let me know if this helps.
Convert JSONArray to arrayList
Aazelix, your Json output seem to be missing opening array bracket.
Its correct form is listed below:
{"output":[{"name":"Name3","URI":"Value3"},{"name":"Name5","URI":"Value5"},{"name":"Name4","URI":"Value4"}]}
As for the conversion to POJO
List<MyObj> list = new ArrayList<>();
if (outputs!= null) {
int len = outputs.length();
for (int i=0; i<len; i++) {
JSONObject o = (JSONObject) outputs.get(i);
list.add(new MyObj(o.getString('name'), o.getString('URL')));
}
}
System.out.println("There is " + list.size() + " objects.");
public static final class MyObj {
final String name;
final String url;
public MyObj(String name, String url) {
this.name = name;
this.url = url;
}
}
Android Volley Convert JSONArray to ArrayList MyObject
If I understand correctly, you better pass in JSONArray instead of string and parse it's contents, like this:
public static List<Beacon> fromJson(JSONArray array)
{
ArrayList<Beacon> res = new ArrayList<>();
for (int i = 0; i < array.length(); ++i)
{
JSONObject beacon = array.getJSONObject(i);
res.add(new Beacon(beacon.getInt("beaconId"), beacon.getString("name"), beacon.getString("imageUrl"))));
}
return res;
}
UPD: in response to your comment, you must use Response.Listener<JSONObject>
instead of Response.Listener<JSONArray>
, and then do this:
public void onResponse(JSONObject response)
{
JSONArray array = response.getJSONArray("data");
converter.fromJson(array);
}
Convert from JSONArray to ArrayList CustomObject - Android
You can convert your JsonArray or json string to ArrayList<OBJECT>
using Gson library as below
ArrayList<OBJECT> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<OBJECT>>(){}.getType());
//or
ArrayList<OBJECT> yourArray = new Gson().fromJson(myjsonarray.toString(), new TypeToken<List<OBJECT>>(){}.getType());
Also while converting your ArrayList<OBJECT>
to JsonArray, no need to convert it to string and back to JsonArray
JsonArray myjsonarray = new Gson().toJsonTree(MyArrayList<OBJECT>).getAsJsonArray();
Refer Gson API documentation for more details. Hope this will be helpful.
Related Topics
Android Studio - Mergedebugresources Exception
Android Alarmmanager Not Working on Some Devices When the App Is Closed
Android: Customize Application's Menu (E.G Background Color)
Cannot Retrieve Field Values from Realm Object, Values Are Null in Debugger
"Rate This App"-Link in Google Play Store App on the Phone
Viewpager with Previous and Next Page Boundaries
Google Play on Android 4.0 Emulator
Fragment Myfragment Not Attached to Activity
Android Customized Button; Changing Text Color
How to Find and Run the Keytool
How to Build the Android Sdk with Hidden and Internal APIs Available
How to Show Enable Location Dialog Like Google Maps
How to _Really_ Programmatically Change Primary and Accent Color in Android Lollipop
Android Textview with Clickable Links: How to Capture Clicks
How to Change the Color of a Checkbox