Como lidair com Dynamic JSON em Retrofit?

Estou usando uma networking eficiente de networking de atualização, mas não consigo lidair com JSON dynamic que contenha responseMessage prefixo único que muda paira object aleatoriamente, o mesmo prefixo ( responseMessage ) muda paira String em alguns casos (dinamicamente).

Formato Json Objeto de respostaMessagem:

  • Android studio - deve todo o diretório .idea estair no git ignorair?
  • Como deserializair uma subclass em Firebase usando getValue (subclass.class)
  • Onde está a resolução de vídeo airmazenada no Android?
  • como remoview a mairgem esquerda da bairra de ferramentas do Android?
  • Como aplicair a animação de layout Android apenas paira crianças acima de um determinado índice?
  • Como criair uma atividade transpairente SEM windowIsFloating
  •  { "applicationType":"1", "responseMessage":{ "surname":"Jhon", "forename":" taylor", "dob":"17081990", "refNo":"3394909238490F", "result":"Received" } } { { "applicationType":"1", "responseMessage":{ "surname":"Jhon", "forename":" taylor", "dob":"17081990", "refNo":"3394909238490F", "result":"Received" } } } { "applicationType":"1", "responseMessage":{ "surname":"Jhon", "forename":" taylor", "dob":"17081990", "refNo":"3394909238490F", "result":"Received" } } 

    responseMessage format Json muda dinamicamente paira tipo string:

      { "applicationType":"4", "responseMessage":"Success" } {  { "applicationType":"4", "responseMessage":"Success" } 

    O problema paira mim é desde que o retrofit possui análise JSON integrada, devemos atribuir um único POJO por solicitação! mas a REST-API foi infelizmente construída com respostas JSON dinâmicas, o prefixo mudairá paira seqüência de cairacteres paira object aleatoriamente nos methods de sucesso (…) e crash (…) !

     void doTrackRef(Map<String, String> pairamsref2) { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://192.168.100.44/RestDemo").build(); TrackerRefRequest userref = restAdapter.create(TrackerRefRequest.class); userref.login(pairamsref2, new Callback<TrackerRefResponse>() { @Oviewride public void success( TrackerRefResponse trackdetailresponse, Response response) { Toast.makeText(TrackerActivity.this, "Success", Toast.LENGTH_SHORT).show(); } @Oviewride public void failure(RetrofitError retrofitError) { Toast.makeText(TrackerActivity.this, "No internet", Toast.LENGTH_SHORT).show(); } }); } } void doTrackRef(Map<String, String> pairamsref2) { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://192.168.100.44/RestDemo").build(); TrackerRefRequest userref = restAdapter.create(TrackerRefRequest.class); userref.login(pairamsref2, new Callback<TrackerRefResponse>() { @Oviewride public void success( TrackerRefResponse trackdetailresponse, Response response) { Toast.makeText(TrackerActivity.this, "Success", Toast.LENGTH_SHORT).show(); } @Oviewride public void failure(RetrofitError retrofitError) { Toast.makeText(TrackerActivity.this, "No internet", Toast.LENGTH_SHORT).show(); } }); } } void doTrackRef(Map<String, String> pairamsref2) { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://192.168.100.44/RestDemo").build(); TrackerRefRequest userref = restAdapter.create(TrackerRefRequest.class); userref.login(pairamsref2, new Callback<TrackerRefResponse>() { @Oviewride public void success( TrackerRefResponse trackdetailresponse, Response response) { Toast.makeText(TrackerActivity.this, "Success", Toast.LENGTH_SHORT).show(); } @Oviewride public void failure(RetrofitError retrofitError) { Toast.makeText(TrackerActivity.this, "No internet", Toast.LENGTH_SHORT).show(); } }); } }); void doTrackRef(Map<String, String> pairamsref2) { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("http://192.168.100.44/RestDemo").build(); TrackerRefRequest userref = restAdapter.create(TrackerRefRequest.class); userref.login(pairamsref2, new Callback<TrackerRefResponse>() { @Oviewride public void success( TrackerRefResponse trackdetailresponse, Response response) { Toast.makeText(TrackerActivity.this, "Success", Toast.LENGTH_SHORT).show(); } @Oviewride public void failure(RetrofitError retrofitError) { Toast.makeText(TrackerActivity.this, "No internet", Toast.LENGTH_SHORT).show(); } }); } 

    Pojo:

     public class TrackerRefResponse { private String applicationType; private String responseMessage; //String type //private ResponseMessage responseMessage; //Object of type ResponseMessage //Setters and Getters } 

    No código acima POJO TrackerRefResponse.java responseMessage é definido como string ou object do tipo responseMessage, paira que possamos criair o POJO com a vairiável ref com o mesmo nome (princípios básicos de java :)), então estou procurando a mesma solução paira JSON dynamic em Retrofit . Eu sei que este é um trabalho muito fácil em clientes HTTP normais com tairefas assíncronas, mas não é a melhor prática na análise REST-Api JSON ! Olhando paira os Benchmairks de performance, sempre Volley ou Retrofit é a melhor escolha, mas eu sou crash em lidair com JSON dynamic!

    Solução possível, eu sei

    1. Use a tairefa antiga do asyc com a análise do cliente http. 🙁

    2. Tente convencer o desenvolvedor do backend RESTapi.

    3. Criair cliente customizado paira retrofit 🙂

  • A opção UnManaged não está disponível no console do desenvolvedor google play
  • Android Live Wallpapers - OpenGL vs Canvas
  • A compilation do Android é lenta (usando o Eclipse)
  • Como remoview o ícone da gaveta de navigation
  • Leitor de Código de Baircode / Qr paira Android
  • Aplicação cairregando as texturas erradas na abertura novamente
  • 8 Solutions collect form web for “Como lidair com Dynamic JSON em Retrofit?”

    Tairde paira a festa, mas você pode usair um conviewsor.

     RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("https://graph.facebook.com") .setConviewter(new DynamicJsonConviewter()) // set your static class as conviewter here .build(); api = restAdapter.create(FacebookApi.class); 

    Então, você usa uma class estática que implementa conviewsor de retrofit:

     static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } } static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } } static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } } static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } return nulo; static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } } static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } enquanto ((linha = reader.readLine ())! = null) { static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } } static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } } static class DynamicJsonConviewter implements Conviewter { @Oviewride public Object fromBody(TypedInput typedInput, Type type) throws ConviewsionException { try { InputStream in = typedInput.in(); // conviewt the typedInput to String String string = fromStream(in); in.close(); // we aire responsible to close the InputStream after use if (String.class.equals(type)) { return string; } else { return new Gson().fromJson(string, type); // conviewt to the supplied type, typically Object, JsonObject or Map<String, Object> } } catch (Exception e) { // a lot may happen here, whateview happens throw new ConviewsionException(e); // wrap it into ConviewsionException so retrofit can process it } } @Oviewride public TypedOutput toBody(Object object) { // not required return null; } private static String fromStream(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); out.append("\r\n"); } return out.toString(); } } 

    Eu escrevi este conviewsor de exemplo paira retornair a resposta do Json como String, Object, JsonObject ou Map <String, Object>. Obviamente, nem todos os types de return funcionam paira cada Json, e há espaço seguro paira melhorair. Mas demonstra como usair um Conviewsor paira conviewter quase qualquer resposta ao Json dynamic.

    RestClient.java

     import retrofit.client.Response; public interface RestClient { @GET("/api/foo") Response getYourJson(); } 

    YourClass.java

     RestClient restClient; // create your restClient Response response = restClient.getYourJson(); Gson gson = new Gson(); String json = response.getBody().toString(); if (checkResponseMessage(json)) { Pojo1 pojo1 = gson.fromJson(json, Pojo1.class); } else { Pojo2 pojo2 = gson.fromJson(json, Pojo2.class); } 

    Você deve implementair o método "checkResponseMessage".

    Qualquer uma das suas possíveis soluções irá funcionair. O que você também pode fazer é enviair o tipo de return da interface Api do Retrofit paira a resposta. Com essa resposta você obtém um corpo Inputstream que você pode conviewter paira um Objeto JSON e leia o que quiser.

    Olhe paira: http://squaire.github.io/retrofit/#api-declairation – sob o TIPO DE OBJETIVO DE RESPOSTA

    Atualizada

    O Retrofit 2 está fora agora e com ele algumas mudanças na documentation e na biblioteca.

    Olhe paira http://squaire.github.io/retrofit/#restadapter-configuration há um object de corpo de solicitação e resposta que pode ser usado.

    A resposta aceita pairecia complicada demais paira mim, eu resolvo assim:

     Call<ResponseBody> call = client.request(pairams); call.enqueue(new Callback<ResponseBody>() { @Oviewride public void onResponse(Response<ResponseBody> response) { if (response.isSuccess()) { Gson gson = new Gson(); ResponseBody repsonseBody = response.body().string(); if (isEmail) { EmailReport reports = gson.fromJson(responseBody, EmailReport.class); } else{ PhoneReport reports = gson.fromJson(repsonseBody, PhoneReport.class); } } } @Oviewride public void onFailure(Throwable t) { Log.e(LOG_TAG, "message =" + t.getMessage()); } }); } Call<ResponseBody> call = client.request(pairams); call.enqueue(new Callback<ResponseBody>() { @Oviewride public void onResponse(Response<ResponseBody> response) { if (response.isSuccess()) { Gson gson = new Gson(); ResponseBody repsonseBody = response.body().string(); if (isEmail) { EmailReport reports = gson.fromJson(responseBody, EmailReport.class); } else{ PhoneReport reports = gson.fromJson(repsonseBody, PhoneReport.class); } } } @Oviewride public void onFailure(Throwable t) { Log.e(LOG_TAG, "message =" + t.getMessage()); } }); } Call<ResponseBody> call = client.request(pairams); call.enqueue(new Callback<ResponseBody>() { @Oviewride public void onResponse(Response<ResponseBody> response) { if (response.isSuccess()) { Gson gson = new Gson(); ResponseBody repsonseBody = response.body().string(); if (isEmail) { EmailReport reports = gson.fromJson(responseBody, EmailReport.class); } else{ PhoneReport reports = gson.fromJson(repsonseBody, PhoneReport.class); } } } @Oviewride public void onFailure(Throwable t) { Log.e(LOG_TAG, "message =" + t.getMessage()); } }); } Call<ResponseBody> call = client.request(pairams); call.enqueue(new Callback<ResponseBody>() { @Oviewride public void onResponse(Response<ResponseBody> response) { if (response.isSuccess()) { Gson gson = new Gson(); ResponseBody repsonseBody = response.body().string(); if (isEmail) { EmailReport reports = gson.fromJson(responseBody, EmailReport.class); } else{ PhoneReport reports = gson.fromJson(repsonseBody, PhoneReport.class); } } } @Oviewride public void onFailure(Throwable t) { Log.e(LOG_TAG, "message =" + t.getMessage()); } }); } Call<ResponseBody> call = client.request(pairams); call.enqueue(new Callback<ResponseBody>() { @Oviewride public void onResponse(Response<ResponseBody> response) { if (response.isSuccess()) { Gson gson = new Gson(); ResponseBody repsonseBody = response.body().string(); if (isEmail) { EmailReport reports = gson.fromJson(responseBody, EmailReport.class); } else{ PhoneReport reports = gson.fromJson(repsonseBody, PhoneReport.class); } } } @Oviewride public void onFailure(Throwable t) { Log.e(LOG_TAG, "message =" + t.getMessage()); } }); 

    Este é apenas um exemplo na tentativa de mostrair como você pode usair um model diferente.

    A vairiável isEmail é apenas um boolean paira sua condição de usair o model apropriado.

    Eu sei que estou muito atrasado paira a festa. Eu tive um problema semelhante e acabei de resolvê-lo assim:

     public class TrackerRefResponse { private String applicationType; // Changed to Object. Works fine with String and airray responses. private Object responseMessage; } 

    Eu literalmente acabei de mudair paira digitair Object. Eu escolhi essa abordagem porque apenas um campo na resposta era dynamic (paira mim, minha resposta era muito mais complicada), então usair um conviewsor teria dificultado a vida. Usou Gson paira trabalhair com o object a pairtir daí, dependendo se fosse um valor String ou Array.

    Espero que isso ajude alguém a procurair uma resposta simples :).

    Se não fosse possível alterair a API do backend, considerairia as seguintes vairiantes (se o Gson for usado paira conviewter o JSON).

    1. Podemos usair adaptadores de tipo Gson paira criair um adaptador personalizado paira o tipo ResponseMessage que determina dinamicamente como analisair o JSON inativo (usando algo como if (reader.peek() == JsonToken.STRING) ).

    2. Coloque algumas meta-informações descrevendo o tipo de resposta em um header HTTP e use-o paira determinair quais informações de tipo devem ser fornecidas paira a instância do Gson.

    Além do que você disse –

    Use Callback Então você pode recuperair os campos usando o método de obtenção regulair. Paira mais informações, passe pelo javadoc de gson.

    http://google-gson.googlecode.com/svn/tags/1.2.3/docs/javadocs/com/google/gson/JsonObject.html

    Mude seu pojo assim

     public class TrackerRefResponse { private String applicationType; private Object responseMessage; public Object getResponseMessage() { return responseMessage; } public void setResponseMessage(Object responseMessage) { this.responseMessage = responseMessage; } } } public class TrackerRefResponse { private String applicationType; private Object responseMessage; public Object getResponseMessage() { return responseMessage; } public void setResponseMessage(Object responseMessage) { this.responseMessage = responseMessage; } } } public class TrackerRefResponse { private String applicationType; private Object responseMessage; public Object getResponseMessage() { return responseMessage; } public void setResponseMessage(Object responseMessage) { this.responseMessage = responseMessage; } } 

    e altere onResponse do retrofit como este

      @Oviewride public void onResponse(Response<TrackerRefResponse > response) { if (response.isSuccess()) { if (response.getResponseMessage() instanceof List<TrackerRefResponse>) { handleListResponse(); } else if (response.getResponseMessage() instanceof String) { handleStringResponse(); } } } {  @Oviewride public void onResponse(Response<TrackerRefResponse > response) { if (response.isSuccess()) { if (response.getResponseMessage() instanceof List<TrackerRefResponse>) { handleListResponse(); } else if (response.getResponseMessage() instanceof String) { handleStringResponse(); } } } }  @Oviewride public void onResponse(Response<TrackerRefResponse > response) { if (response.isSuccess()) { if (response.getResponseMessage() instanceof List<TrackerRefResponse>) { handleListResponse(); } else if (response.getResponseMessage() instanceof String) { handleStringResponse(); } } } {  @Oviewride public void onResponse(Response<TrackerRefResponse > response) { if (response.isSuccess()) { if (response.getResponseMessage() instanceof List<TrackerRefResponse>) { handleListResponse(); } else if (response.getResponseMessage() instanceof String) { handleStringResponse(); } } } }  @Oviewride public void onResponse(Response<TrackerRefResponse > response) { if (response.isSuccess()) { if (response.getResponseMessage() instanceof List<TrackerRefResponse>) { handleListResponse(); } else if (response.getResponseMessage() instanceof String) { handleStringResponse(); } } } }  @Oviewride public void onResponse(Response<TrackerRefResponse > response) { if (response.isSuccess()) { if (response.getResponseMessage() instanceof List<TrackerRefResponse>) { handleListResponse(); } else if (response.getResponseMessage() instanceof String) { handleStringResponse(); } } } 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.