简体   繁体   中英

Extract json data from an api array or matrix java android studio

I can't extract data from this json. I believe it is because it is an array. I read about it but I didn't find anything specific for this case.

I just need to take the values individually each time I close {}.

Eg: result [0].getLoterias();

== INSTANTANEA

The connection is being made normally, I just can't extract the data.

httpservice2.java

package br.com.matheuscastiglioni.blog.requisicao_http.service;

import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;

public class HttpService2 extends AsyncTask<Void, Void, CEP2> {


    private final String cep;
    private final String token;

    public HttpService2(String cep, String token) {
        this.cep = token;
        this.token = cep;

    }

    @Override
    protected CEP2 doInBackground(Void... voids) {
        StringBuilder resposta = new StringBuilder();



            try {
                URL url = new URL( "A" + this.cep + "&token=" + this.token);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-type", "application/json");
                connection.setRequestProperty("Accept", "application/json");
                connection.setDoOutput(true);
                connection.setConnectTimeout(5000);
                connection.connect();

                Scanner scanner = new Scanner(url.openStream());
                while (scanner.hasNext()) {
                    resposta.append(scanner.next());
                }



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



            return new Gson().fromJson(resposta.toString(), CEP2.class);
    }



}

Main3Activity.java:

package br.com.matheuscastiglioni.blog.requisicao_http;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.concurrent.ExecutionException;

import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;
import br.com.matheuscastiglioni.blog.requisicao_http.service.HttpService2;

public class Main3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);


        final TextView resposta = findViewById(R.id.etMain_resposta2);
        final TextView cep = findViewById(R.id.etMain_resposta3);
        final TextView token = findViewById(R.id.etMain_resposta4);
        Bundle extras = getIntent().getExtras();
        String respostatoken = extras.getString("token");
        String respostaid = extras.getString("id");

        cep.setText(respostaid);
        token.setText(respostatoken);
//alert(cep.getText().toString() + token.getText().toString());
          try {
              CEP2 retorno = new HttpService2(cep.getText().toString(), token.getText().toString()).execute().get();
              String loteria = retorno.getIdloteria();
            resposta.setText(loteria);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    private void alert(String s) {
        Toast.makeText(this,s,Toast.LENGTH_LONG).show();
    }
}

CEP2.java:

package br.com.matheuscastiglioni.blog.requisicao_http.model;



public class CEP2 {


    private String idloteria;

    public String getIdloteria() {
        return idloteria;
    }

    public void setIdloteria(String idloteria) {
        this.idloteria = idloteria;
    }



}

currently:

I changed

return new Gson().fromJson(resposta.toString(), CEP2.class);

per

Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;

httpservic2 new:

package br.com.matheuscastiglioni.blog.requisicao_http.service;

import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import br.com.matheuscastiglioni.blog.requisicao_http.model.CEP2;

public class HttpService2 extends AsyncTask<Void, Void, CEP2> {


    private final String cep;
    private final String token;

    public HttpService2(String cep, String token) {
        this.cep = token;
        this.token = cep;

    }

    @Override
    protected CEP2 doInBackground(Void... voids) {
        StringBuilder resposta = new StringBuilder();



            try {
                URL url = new URL( "A" + this.cep + "&token=" + this.token);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-type", "application/json");
                connection.setRequestProperty("Accept", "application/json");
                connection.setDoOutput(true);
                connection.setConnectTimeout(5000);
                connection.connect();

                Scanner scanner = new Scanner(url.openStream());
                while (scanner.hasNext()) {
                    resposta.append(scanner.next());
                }



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



               Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
        List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
        return cep2List;
    }



}

I need to change the return from doinbackground However, I'm lost

It seems you only want the idloteria from the response which should be fine. But as you say it's an array and it should be parsed as an array or a List.

The:

return new Gson().fromJson(resposta.toString(), CEP2.class);

Should be

Type cep2ListType = new TypeToken<ArrayList<CEP2>>(){}.getType();
List<CEP2> cep2List = new Gson().fromJson(resposta.toString(), cep2ListType);
return cep2List;

If you want the response be parsed as a list.

Another possibility is to get the data parsed as an array:

CEP2[] cep2Array = new Gson().fromJson(resposta.toString(), CEP2[].class);
return cep2Array;

and you'll need to change the return of the doInBackground in accordance with the response type you choose.

Lets choose to return a list. In this case change AsyncTask<Void, Void, CEP2> to AsyncTask<Void, Void, List<CEP2>> and also protected CEP2 doInBackground to protected List<CEP2> doInBackground . The returned list will be received in onPostExecute parameter onPostExecute(List<CEP2> cep2List) . And in this onPostExecute you can save the list, print it or do whatever you want to do with the received data.

But keep in mind that AsyncTask are deprecated in API level R. It's recommended using standard java.util.concurrent or Kotlin concurrency utilities instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM