Extract data from JSON within JSON that they see from a Web Service serving an Android APP

Asked

Viewed 648 times

1

Good night, guys, how are you? I am developing an Android APP and it consumes data from a webservice, but I’m having trouble bringing some information to the APP.

This is the JSON I return to my APP:

{
    "cod":1
    ,"dados":
        {
            "key":"123",
            "time":"123"
        }
    ,"msg":"ola"
}

As you can see there is a main JSON and within it there is another JSON in the index dados the information of cod and msg I’m managing to recover normally but JSON son (dados) can’t recover. remembering that I’m using the Retrofit 2 and JAVA (without any framework in case) to communicate with the webservice. Can you give me a light? Because I have no idea what to do. It follows classes:

Dataswebservice.java

import com.google.gson.annotations.SerializedName;

import org.json.JSONObject;

public class DatasWebService {

    @SerializedName("cod")
    private int cod;

    @SerializedName("msg")
    private String msg;

    @SerializedName("dados")
    private JSONObject dados;

    public int getCod() {
        return cod;
    }

    public void setCod(int cod) {
        this.cod = cod;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public JSONObject getDados() {
        return dados;
    }

    public void setDados(JSONObject dados) {
        this.dados = dados;
    }

    @Override
    public String toString() {
        return "DatasWebService{" +
                "cod=" + cod +
                ", msg='" + msg + '\'' +
                ", dados=" + dados +
                '}';
    }
}

Java data.:

final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                  .connectTimeout(60, TimeUnit.SECONDS)
                  .readTimeout(60, TimeUnit.SECONDS)
                  .writeTimeout(60, TimeUnit.SECONDS)
                  .build();

Retrofit retrofit = new Retrofit
        .Builder()
        .baseUrl(Helper.URLAPI)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

DadosDao dDao = new DadosDao(context);

try {

    // VARIÁVEL CRIADA EM OUTRA PARTE DO ARQUIVO, NÃO TEM PROBLEMA COM ELA
    dados.put("key", dDao.getKey());

    WebService cadWebService = retrofit.create(WebService.class);

    Call<DatasWebService> call = cadWebService.datasWebService(acao, dados);

    call.enqueue(new Callback<DatasWebService>() {
        @Override
        public void onResponse(Call<DatasWebService> call, Response<DatasWebService> response) {
            DatasWebService datasWebService = response.body();

            if ((datasWebService != null) && (datasWebService.getCodStatus() == 1)) {

                try {
                    // AQUI ESTA O PROBLEMA, ELE RETORNA VAZIO MESMO O WEBSERVICE ENVIANDO O JSON, TENHO CERTEZA QUE O JSON É RETORNADO POIS COLOQUEI PRA ESCREVER NO LOG DO WEBSERVICE
                    Log.i("log", datasWebService.getDados().getString("key")); 
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                // FAZER TRATAMENTO DE RETORNO
            }
        }

        @Override
        public void onFailure(Call<DatasWebService> call, Throwable t) {

        }
    });


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

Webservice.java IT’S NOT THE SERVER! IT’S AN APP INTERFACE

import org.json.JSONObject;

import io.domain.requests.DatasWebService;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface WebService {

    @FormUrlEncoded
    @POST("index.php")
    Call<DatasWebService> datasWebService(@Field("acao") String acao, @Field("dados") JSONObject dados);
}

1 answer

1


Try creating a class called Data with the attributes you need to recover and then replace the Jsonobject data attribute with it.

public class Dados {
    public String key;
    public String time;
    // criar getter e setters
 }


public class DatasWebService {

    @SerializedName("cod")
    private int cod;

    @SerializedName("msg")
    private String msg;

    @SerializedName("dados")
    private Dados dados;

    // criar getter e setters
}
  • Good idea, I will do the test, but you do not know another method that can recover all values, without having to define before what will be returned? Because I wanted to do it in a generic way so I didn’t have to define in the APP each information that the webservice will return, would save work and the code would be cleaner.

  • 1

    Generally speaking you may be able to use Jsonobject, but it might be more difficult to implement.

  • Right and do you know any way? Because I couldn’t do it and I’ve been searching since yesterday morning and I haven’t found anything on the web that fits.

  • 1

    You can turn your json into a Linkedhashmap and then access the data through the key. I just don’t think this is a very elegant solution. Objectmapper mapper = new Objectmapper(); Linkedhashmap<String, Object> Object = new Linkedhashmap<>(); Object = mapper.readValue(json, new Typereference<Linkedhashmap<String, Object>>(){});

  • OK I’ll be checking the two options I’ll give you news after this... Thanks meanwhile.

  • Making this new class worked, is not the way I would like, but for now this good. Thank you.

Show 1 more comment

Browser other questions tagged

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