Jsonarray in Jsonobject: Json.typeMistach error

Asked

Viewed 709 times

4

In a web search I discovered that the Json.typeMistach error was due to I’m getting one JSONArray and trying to arrow it into a JSONObject.

Turns out I can’t fix it, the mistake persists.

Could someone give me a hand or show me 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();
    }
}

2 answers

5

You get a JSONArray, just need to travel it 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: Oficina Beira Mar
id: 19838 - boy_code: Oficina Beira Mar
id: 19948 - boy_code: Oficina Beira Mar

  • 1

    Thank you very much re22.

2

A solution similar to the R22 that I had found. Only so that people can use based on understanding also.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.