Transform Jsonarray into Class Object

Asked

Viewed 148 times

2

I am consuming an API in my application that returns me an array of names, I created a class to assign each name to 1 instance but I am having problems to take this Jsonarray and transform into object, all the methods I tried did not work, someone knows how to do this in Java (Android) ?

public void jsonToObj(JSONArray resultadoDaPesquisa) {

    try {
        JSONObject jsonObject = null;
        JSONArray jsonArray = resultadoDaPesquisa;

        jsonObject = new JSONObject(resultadoDaPesquisa.toString());
        System.out.println("resultado " + jsonObject);


    } catch (Exception e) {
        e.printStackTrace();
    }


}

org.json.Jsonexception: Value [{"id":67377,"name":"Shiren the Wanderer 4: The Eye of God and the Devil’s Navel"}] of type org.json.Jsonarray cannot be converted to Jsonobject

  • Welcome to Stackoverflow Lucas. Please post an excerpt of the code you already have to get a better idea of the problem, I suggest you read this help article from the site: How to create a Minimum, Complete and Verifiable example.

  • Lucas, edit your question by posting the code you already tried. Remember, this is a site that revolves around codes. Without them, little or no help will be able to offer you.

  • Edited. Now with one of several codes I tried.

  • Lucas, it would be good to see the json. It could stick here for us!

  • The Jsonarray is this: [{"id":67377,"name":"Shiren the Wanderer 4: The Eye of God and the Devil’s Navel"}] returns to me an id and a name, what you want ?

3 answers

0

This is the code I use to be JSON and turn into object:

public class JsonReader {

    static String secretKeyCaptcha = "6Ld5NXMUAAAAAOXPv-EbwycOMHfoxJrSSdLcLl-I";

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromUrl(String cep) throws IOException, JSONException {
        InputStream is = new URL("https://viacep.com.br/ws/" + cep + "/json/").openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }

    public static JSONObject validarTokenRecaptcha(String token) throws IOException {
        System.out.println("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKeyCaptcha + "&response=" + token);
        InputStream is = new URL(
                "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKeyCaptcha + "&response=" + token)
                        .openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }
}

Then just do it:

            JSONObject jsonObj = new JSONObject();
            JsonReader jr = new JsonReader();
            jsonObj = jr.readJsonFromUrl(frete.getCepDestino());

enderecoDestino = jsonObj.get("logradouro").toString() + " - " + jsonObj.get("bairro").toString()

0

Thanks for the help ! I managed to do it another way.

    JSONObject jsonObject = null;
    try {
        for(int i = 0; i<resultadoDaPesquisa.length(); i++) {
            jsonObject = resultadoDaPesquisa.getJSONObject(i);
            String id = jsonObject.getString("id");
            String nome = jsonObject.getString("name");

            Anuncio anuncio = new Anuncio();
            anuncio.setUid(id);
            anuncio.setTitulo(nome);

            System.out.println(anuncio);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }


}

0

You can use the library GSON to facilitate the work.

With it, from the JSON string you receive, you can create an instance of the desired class.

Take an example:

Gson gson = new Gson();
SuaClasse suaClasse = gson.fromJson(stringJson, SuaClasse.class);

Here is the lib User’s Guide.

  • I tried, but I couldn’t because I was a Jsonarray, maybe I was doing wrong or needed a conversion.

Browser other questions tagged

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