Android JSON Get getObjectArray(JSONArray jsonArray, Class clazz)

Here you can find the source of getObjectArray(JSONArray jsonArray, Class clazz)

Description

A helper method to convert multi dimensional JSONArrays to ObjectArrays of Class clazz.

Parameter

Parameter Description
jsonArray the JSONArray to convert

Exception

Parameter Description
JSONException exception during JSON parsing

Return

clazzArray and array of Objects from type clazz

Declaration

@SuppressWarnings("unchecked")
public static <K> K[] getObjectArray(JSONArray jsonArray, Class<K> clazz) 

Method Source Code

//package com.java2s;

import java.lang.reflect.Array;

import org.json.JSONArray;

import org.json.JSONObject;

public class Main {
    /**/*from  w  w  w  . j  a  va2 s .co  m*/
     * A helper method to convert multi dimensional JSONArrays to ObjectArrays
     * of Class clazz.
     * @param jsonArray the JSONArray to convert
     * @return clazzArray and array of Objects from type clazz
     * @throws JSONException exception during JSON parsing
     */
    @SuppressWarnings("unchecked")
    public static <K> K[] getObjectArray(JSONArray jsonArray, Class<K> clazz) {
        K[] result = (K[]) Array.newInstance(clazz, jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                result[i] = clazz.getConstructor(JSONObject.class)
                        .newInstance(jsonArray.getJSONObject(i));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

Related

  1. JSONToMap(JSONObject obj)
  2. jsonToDate(String jsonString)
  3. jsonToByteBuffer(JSONObject jsonObj)