JSONArray in JSONObject: Json.typeMistach error

4

In a web-based search I discovered that the Json.typeMistach error was due to me getting a JSONArray and trying to get it in a JSONObject .

I can not fix it, the error persists.

Could someone give me a hand or point me to a tutorial for the problem?

My JSON :

[
   {
      "id":19761,
      "nome_oficina":"Oficina Beira Mar"
   },
   {
      "id":19838,
      "nome_oficina":"Oficina Beira Mar"
   },
   {
      "id":19948,
      "nome_oficina":"Oficina Beira Mar"
   }
]

My code to convert JSONArray to JSONObject :

private void parseJson(String data) {

    String strJson=data;

    try {
    JSONObject jsnJsonObject = new JSONObject(strJson);
    JSONArray contacts = jsnJsonObject.getJSONArray("NAO SEI O QUE POR AQUI, JÁ QUE MINHA STRING NÃO SE INICIA COM TIPO DO OBJETO");

        for (int i = 0; i < contacts.length(); i++)
        {       
            JSONObject c = contacts.getJSONObject(i);
            String id = c.getString("id");
            String boy_code = c.getString("nome_oficina");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
    
asked by anonymous 10.09.2015 / 04:24

2 answers

4

You get a JSONArray , you only have to go through it by accessing each index (which is a JSONObject ):

private static void parseJson(String data){    
    try {
        JSONArray array = new JSONArray(data);

        // Percorrendo cada índice
        for(int i = 0; i < array.length(); i++){

            // Obtendo o objeto do índice atual
            JSONObject json = array.getJSONObject(i);

            String id = json.get("id").toString();
            String boy_code = json.get("nome_oficina").toString();                
            System.out.println("id: " + id + " - boy_code: " + boy_code);
        }       
    } catch(JSONException err){
        // Tratamento de exceções
    }
}

output:

  

id: 19761 - boy_code: Office Beira Mar
  id: 19838 - boy_code: Office Beira Mar
  id: 19948 - boy_code: Beira Mar Office

    
10.09.2015 / 05:02
2

A solution similar to that of r22 I had found. Just so people can use basic understanding too.

    try {
            JSONArray jsonArray = new JSONArray(SetServerString);

            for (int i = 0; i < jsonArray.length(); ++i) {
                JSONObject rec = jsonArray.getJSONObject(i);
                int id = rec.getInt("id");
               Log.i("__PRINT__",String.valueOf(id));

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    
10.09.2015 / 14:18