2

i have JSONArray(not JSONObject) , content of this array looks like :

[{"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"}]

Now i need to convert it to ArrayList ,i was looking for different manuals , but and try some code:

My 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;
}

My 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());
        }

    }
}

}

When i start my program and click on button to show array in logs i have this

  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

I understand that i make mistake in my JSONParcer class, but can u explain me what i need to change in it? Just rename JSONObject to JSONArray didnt work correctly. Thanks for answers

Ololoking
  • 1,577
  • 4
  • 22
  • 37

3 Answers3

1

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 Persons. Let me know if this helps.

iRuth
  • 2,737
  • 3
  • 27
  • 32
  • i tried your solution, and it nothng showed in logs , i didnt understand why its happend – Ololoking Feb 21 '15 at 22:42
  • nothing, i add button.setbtn.setEnabled false and true to see when the process ended , process end and nothing happend – Ololoking Feb 21 '15 at 22:55
  • may be it didnt show because my arraylist didnt create correctly? – Ololoking Feb 21 '15 at 23:13
  • i want to see in logs : "Works" id : 1 cardName :test cardHolder:.. etc.;works id : 2 cardName: test2 ; cardHolder:... etc .. So i want to see full Array of Cards which i have on my server – Ololoking Feb 22 '15 at 10:57
  • have u any ideas why logs didnt show ? i call AsyncTask in button click : new JsonParce().execute(); – Ololoking Feb 22 '15 at 11:01
  • @Ololoking The logs are not showing because `getArrayOfWebData` is empty. You initialized it twice. You should initialize it just once and make your `getJSONFromUrl` return it. Try putting the logs in your `getJSONFromUrl` method to confirm that it is not empty in there. – iRuth Feb 22 '15 at 12:31
  • one more question, so how can i call my `getArrayOfWebData` from **JSONParcer class** in **MainActivity** for example to get array.size? – Ololoking Feb 22 '15 at 13:26
0

As json string is provided in post is JSONArray of JSONObject instead of JSONObject. so need to get JSONArray from response of api.

Make following change in getJSONFromUrl method:

1. Change getJSONFromUrl method return type to JSONArray from JSONObject

2. Convert response string to JSONArray instead of JSONObject:

jsonArray = new JSONArray(json);

3. Return jsonArray from getJSONFromUrl

4. In MainActivity class get JSONArray from getJSONFromUrl method:

JSONArray json = jsonParcer.getJSONFromUrl(url1);

5. Also change doInBackground method return type to JSONArray

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

You can parse it like what you are using or you can do the same with more less code and more performance by using Gson as described in this answer or you can use Jackson as described here.

Community
  • 1
  • 1
Ahmed Hegazy
  • 12,395
  • 5
  • 41
  • 64