如何将JSONArray转换为arraylist

时间:2015-02-21 15:08:53

标签: android arraylist android-json

我有JSONArray(不是JSONObject),这个数组的内容如下:

[{"ID":"24","CardName":"Gool","CardCode":"9785898080617","CardCodeType":"EAN-13","CardHolderName":"\u041f\u0443\u043f\u043a\u0438\u043d","CardCountryCode":"UA","CardHolderID":"3","CardSumRait":"55","VotesCount":"11","Rating":"5"},{"ID":"25","CardName":"XCode","CardCode":"9785898080617","CardCodeType":"EAN-13","CardHolderName":"\u041f\u0443\u043f\u043a\u0438\u043d","CardCountryCode":"UA","CardHolderID":"3","CardSumRait":"31","VotesCount":"8","Rating":"3.875"}]

现在我需要将它转换为ArrayList,我正在寻找不同的手册,但是尝试一些代码:

我的 JSONParcer

public class JSONParcer {

ArrayList<Person> getArrayOfWebData = new ArrayList<Person>();
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";

//конструктор
public JSONParcer() {

}
class Person {
    public String cardID;
    public String cardName;
    public String cardCode;
    public String cardCodeType;
    public String cardHolderName;
    public String cardCountryCode;
    public String cardHolderID;
    public String cardSumRait;
    public String votesCount;
    public String rating;
}

public JSONObject getJSONFromUrl(String url) {
    //делаем HTTP запрос

    try {
        //default HTTP client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();


    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    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 {
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON parcer" , "Error parcing data " +e.toString());
    }
    try{
        JSONArray 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 jsonObject;
}

我的 MainActivity

public class MainActivity extends ActionBarActivity {


String jsonString;
Button btn;

ArrayList<Person> getArrayOfWebData = new ArrayList<Person>();

public void showArrayinLogs(View view) {
    new JsonParce().execute();
}

class Person {
    public String cardID;
    public String cardName;
    public String cardCode;
    public String cardCodeType;
    public String cardHolderName;
    public String cardCountryCode;
    public String cardHolderID;
    public String cardSumRait;
    public String votesCount;
    public String rating;
}

String url1 = "/*my url here*/";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public class JsonParce extends AsyncTask<String , String, JSONObject>{

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParcer jsonParcer = new JSONParcer();
        JSONObject json = jsonParcer.getJSONFromUrl(url1);
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject ) {
        int a = getArrayOfWebData.size();
        for(int i =0 ; i<a ; i++){
            Log.i("WORKS", getArrayOfWebData.get(i).toString());
        }

    }
}

}

当我启动程序并单击按钮以在日志中显示数组时,我有这个

  Value [{"Rating":"5","CardName":"Gool","VotesCount":"11","CardSumRait":"55","CardHolderName":"Пупкин","ID":"24","CardCountryCode":"UA","CardHolderID":"3","CardCode":"9785898080617","CardCodeType":"EAN-13"},{"Rating":"3.875","CardName":"XCode","VotesCount":"8","CardSumRait":"31","CardHolderName":"Пупкин","ID":"25","CardCountryCode":"UA","CardHolderID":"3","CardCode":"9785898080617","CardCodeType":"EAN-13"}] of type org.json.JSONArray cannot be converted to JSONObject

我知道我在 JSONParcer 课程中犯了错误,但你可以解释一下我需要改变的内容吗?只是将JSONObject重命名为JSONArray无法正常工作。谢谢你的回答

3 个答案:

答案 0 :(得分:1)

问题出在您的JSONParcer课程中。在下面的代码中,您尝试从JSON数组(json)创建一个JSON对象,这就是您收到错误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());
}

解决此问题的方法是删除代码的那一部分,因为您正在阅读json两次。

你已经在这里正确地做了 - &gt; 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;
}

然后在MainActivity中,将doInBackground返回的对象,对象输入类型更改为AsyncTask,将对象输入类型更改为onPostExecute更改为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());
        }

    }
}
}

修改

根据您的评论我更新了我的答案。您的JsonParce AsyncTask现在返回ArrayListPerson。如果这有帮助,请告诉我。

答案 1 :(得分:0)

由于json字符串在post中提供的是JSONArray of JSONObject而不是JSONObject。所以需要从api的响应中获取JSONArray。

getJSONFromUrl方法中进行以下更改:

1。getJSONFromUrl

JSONArray方法返回类型更改为JSONObject

2. 将响应字符串转换为JSONArray而不是JSONObject

jsonArray = new JSONArray(json);

3。jsonArray

返回getJSONFromUrl

4。MainActivity班级JSONArray方法中获取getJSONFromUrl

JSONArray json = jsonParcer.getJSONFromUrl(url1);

5。同时将doInBackground方法返回类型更改为JSONArray

答案 2 :(得分:0)

您可以像使用的那样对其进行解析,或者使用Gson中所述answer使用Jackson,您可以使用更少的代码和更高的性能来执行相同操作,或者使用here正如{{3}}所述。