Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Cursor from JSONArray?

I have an adapter class which is extending GroupingCursorAdapter and constructor of type Adapter_Contacts(Context context, Cursor cursor, AsyncContactImageLoader asyncContactImageLoader).

I want to use this same class for populating my ListView. I am getting data from one web service which is JSON.

So my question is that, how can I convert a JSONArray to Cursor to use same adapter class?

like image 266
uniruddh Avatar asked Dec 27 '13 08:12

uniruddh


People also ask

How can I turn a JSONArray into a JSONObject?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

What is the use of JSONArray?

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.

How do you initiate JSONArray?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

What is JSONObject and JSONArray in Java?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.


1 Answers

So my question is that, how can I convert a JSONArray to Cursor to use same adapter class?

You can convert that JSONArray to a MatrixCursor:

// I'm assuming that the JSONArray will contain only JSONObjects with the same propertties
MatrixCursor mc = new MatrixCursor(new String[] {"columnName1", "columnName2", /* etc*/}); // properties from the JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jo = jsonArray.getJSONObject(i);
      // extract the properties from the JSONObject and use it with the addRow() method below 
      mc.addRow(new Object[] {property1, property2, /* etc*/});
}
like image 151
user Avatar answered Oct 16 '22 19:10

user