为什么onResponse方法不起作用? Retrofit2库

时间:2018-10-23 08:57:58

标签: android json get retrofit2

我想使用Retrofit2和Gson库以GET方式接收Json的字符串列表。当我使用POSTMAN从.../titlefaqsjson?_format=json进行GET时,我会以这种方式收到Json:

[
{
    "tid": [
        {
            "value": 27
        }
    ],
    "uuid": [
        {
            "value": "b3d3c5bb-6a8b-40c1-bafe-d4ddf3a45ff3"
        }
    ],
    "langcode": [
        {
            "value": "en"
        }
    ],
    "vid": [
        {
            "target_id": "faq",
            "target_type": "taxonomy_vocabulary",
            "target_uuid": "a225614a-917b-4b0d-861b-9113d5a47fa3"
        }
    ],
    "name": [
        {
            "value": "Buscar una SocialFood"
        }
    ],
    "description": [
        {
            "value": null,
            "format": null,
            "processed": ""
        }
    ],
    "weight": [
        {
            "value": 0
        }
    ],
    "parent": [],
    "changed": [
        {
            "value": "2018-05-31T11:42:24+00:00",
            "format": "Y-m-d\\TH:i:sP"
        }
    ],
    "default_langcode": [
        {
            "value": true
        }
    ],
    "path": [
        {
            "alias": "/faq/soy-socialguest/buscar-una-socialfood",
            "pid": 35,
            "langcode": "en"
        }
    ]
},
{
    "tid": [
        {
            "value": 28
        }
    ],
    "uuid": [
        {
            "value": "e2d05fc8-840c-4cc2-8df2-2cd2bf45ee85"
        }
    ],
    "langcode": [
        {
            "value": "en"
        }
    ],
    "vid": [
        {
            "target_id": "faq",
            "target_type": "taxonomy_vocabulary",
            "target_uuid": "a225614a-917b-4b0d-861b-9113d5a47fa3"
        }
    ],
    "name": [
        {
            "value": "Cancelar una reserva antes de la SocialFood"
        }
    ],
    "description": [
        {
            "value": null,
            "format": null,
            "processed": ""
        }
    ],
    "weight": [
        {
            "value": 1
        }
    ],
    "parent": [],
    "changed": [
        {
            "value": "2018-05-31T11:53:54+00:00",
            "format": "Y-m-d\\TH:i:sP"
        }
    ],
    "default_langcode": [
        {
            "value": true
        }
    ],
    "path": [
        {
            "alias": "/faq/soy-socialguest/cancelar-una-reserva-antes-de-la-socialfood",
            "pid": 36,
            "langcode": "en"
        }
    ]
}, etc..

我具有以这种方式声明GET的接口:

public interface ApiSocialFood {
   @GET("titlefaqsjson?_format=json")
   Call<ResponseFaqs> faqs();
}

ResponseFaqs对象的类是一个简单的类,以字符串列表作为属性,构造函数以及相应的getter和setter。

接收到的Json的Desserializer代码为:

public class FaqsDeserializador implements JsonDeserializer {

@Override
public ResponseFaqs deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    JsonArray arrayJson = json.getAsJsonObject().get("name").getAsJsonArray();
    List<String> lista= new ArrayList<String>();

    for (int i=0;i<arrayJson.size();i++){
        Log.d("xxx",arrayJson.get(i).getAsJsonObject().get("value").getAsString());
        lista.add(arrayJson.get(i).getAsJsonObject().get("value").getAsString());
    }

    ResponseFaqs respuesta = new ResponseFaqs(lista);


    return respuesta;
}
}

我通过以下方式在Activity的onCreate方法中执行所有操作:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity__preguntas__frecuentes);
    tvTitulo1= (TextView) findViewById(R.id.textView13);



    GsonBuilder builder=new GsonBuilder();
    builder.registerTypeAdapter(ResponseFaqs.class,new FaqsDeserializador());

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Api.URL_BASE)
            .addConverterFactory(GsonConverterFactory.create(builder.create()))
            .build();


    ApiSocialFood Service = retrofit.create(ApiSocialFood.class);
    Call<ResponseFaqs> peticionFaqs=Service.faqs();
    peticionFaqs.enqueue(new Callback<ResponseFaqs>() {
        @Override
        public void onResponse(Call<ResponseFaqs> call, Response<ResponseFaqs> response) {

            if (response.code()== HttpURLConnection.HTTP_OK) {
                Toast.makeText(Activity_Preguntas_Frecuentes.this, "DENTRO DE LA IMAGEN", Toast.LENGTH_LONG).show();
                List<String> listafaqs = response.body().getListafaqs();
                tvTitulo1.setText(listafaqs.get(0));

            }else{
                Toast.makeText(Activity_Preguntas_Frecuentes.this, "NO HTTP_OK", Toast.LENGTH_SHORT).show();
            }
            }

        @Override
        public void onFailure(Call<ResponseFaqs> call, Throwable t) {
            Toast.makeText(Activity_Preguntas_Frecuentes.this,"FALLO CONEXION",Toast.LENGTH_SHORT);
        }
    });

}

但是,当我输入要在任何时候加载列表的活动时,程序将进入OnResponse方法。为什么不输入?我以相同的方式获取另一个json的名称和url,并且效果很好,我不知道为什么在这种情况下不起作用。

预先感谢:)

1 个答案:

答案 0 :(得分:0)

我找到了解决方法!

在计算机科学中,大多数时候,错误都是您所错过的愚蠢。

在这种情况下,返回的Json以arrayJson开头,而不是以Json对象开头,因此您所要做的就是添加反序列化此步骤的方法。

反序列化类如下:

公共类FaqsDeserializador实现JsonDeserializer {

@Override
public ResponseFaqs deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    JsonArray arrayJson = json.getAsJsonArray();
    List<String> lista= new ArrayList<String>();

    for (int i=0;i<arrayJson.size();i++){
        Log.d("SocialFoodAPPAlvaro",arrayJson.get(i).getAsJsonObject().get("name").getAsJsonArray().get(0).getAsJsonObject().get("value").getAsString());
        lista.add(arrayJson.get(i).getAsJsonObject().get("name").getAsJsonArray().get(0).getAsJsonObject().get("value").getAsString());
    }

    ResponseFaqs respuesta = new ResponseFaqs(lista);


    return respuesta;
}