简体   繁体   English

从 api 数组或矩阵 java ZC31B32364CE19CA8FCD150A417ECCE5 中提取 json 数据

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

I can't extract data from this json.我无法从此 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();例如:结果 [0].getLoterias();

== INSTANTANEA == 瞬间

The connection is being made normally, I just can't extract the data.连接正常,我只是无法提取数据。

httpservice2.java 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: 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: 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: httpsservic2 新:

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我需要从 doinbackground 更改返回但是,我迷路了

It seems you only want the idloteria from the response which should be fine.看来您只想要响应中的 idloteria 应该没问题。 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.并且您需要根据您选择的响应类型更改 doInBackground 的返回。

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 .在这种情况下,将AsyncTask<Void, Void, CEP2>更改为AsyncTask<Void, Void, List<CEP2>>并将protected CEP2 doInBackgroundprotected List<CEP2> doInBackground The returned list will be received in onPostExecute parameter onPostExecute(List<CEP2> cep2List) .返回的列表将在 onPostExecute 参数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.在这个 onPostExecute 中,您可以保存列表、打印它或对接收到的数据做任何您想做的事情。

But keep in mind that AsyncTask are deprecated in API level R.但请记住, AsyncTask 在 API 级别 R 中已弃用 It's recommended using standard java.util.concurrent or Kotlin concurrency utilities instead.建议改用标准 java.util.concurrent 或 Kotlin 并发实用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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