繁体   English   中英

如何使用 retrofit 存储 json 数组响应

[英]how to store json array response using retrofit

我想调用 api 端点并在我的 android 应用程序中显示相关响应。 api 采用参数 user_name 并返回该用户的响应。 响应在 json 数组中,包括日期、位置和 img (base64) 的 json。

回复

[
   {
        "id": "602a1901a54781517ecb717c",
        "date": "2021-02-15T06:47:29.191000",
        "location": "mall",
        "img": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCASvBLADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/
}
]

我面临的问题是我无法存储响应并对其进行解析。 我为此使用 retrofit。 api 调用中没有问题,服务器获得成功的请求,问题出在客户端(android 应用程序)。 这是我目前拥有的代码。 ApiInterface.java

interface ApiInterface {  
    @FormUrlEncoded  
    @POST("end_point")  
    Call<List<Task>>getstatus(@Field("user_name") String user_name);  
  }

任务.java

public class Task {  
  @SerializedName("user_name")  
  public String user_name;  
  public Task(String user_name) {  
      user_name = user_name.substring(1, user_name.length()-1);  
      this.user_name= user_name;  
  }  
  public String getUser() {  
      return user_name;  
  }
  }

MainActivity.java

private void LoginRetrofit(String user_name) {  
    Retrofit retrofit = new Retrofit.Builder()  
            .baseUrl("url")  
            .addConverterFactory(GsonConverterFactory.create())  
            .build();  
  
    final ApiInterface request = retrofit.create(ApiInterface.class);  
    Call<List<Task>> call = request.getstatus(user_name);  
    Toast.makeText(getApplicationContext(), "user_name" + " " + call.request(), Toast.LENGTH_LONG).show();  
    call.enqueue(new Callback<List<Task>>() {  
        @Override  
  public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {  
            try { 
                List<Task> rs=response.body();  
                Toast.makeText(getApplicationContext(), "Response" +  " "+rs, Toast.LENGTH_LONG).show();  
            }  
            catch (Exception e)  
            {  
                Log.d("REsponse error",e.getMessage());  
            }  
        }  
  
        @Override  
  public void onFailure(Call<List<Task>> call, Throwable t) {  
            Log.d("Error",t.getMessage());  
        }  
    });    
}

This is the response which is being returned.

Your data model class variables should be serialized or to have names as same as in the response, so that retrofit can be able to bind response values to your model variables. 此外,对于要使用的响应中的每个键值对,您的 model class 中必须有一个变量。

检查此示例以了解 retrofit 的实际工作原理。

MainActivity.java文件中,更新如下代码,因为您在 toast 消息中打印rs object,它只打印object 地址而不是其中的值。 所以要打印你收到的 object 的值,你必须调用 object 的方法来得到类似的值。

MainActivity.java

private void LoginRetrofit(String user_name) {  
    Retrofit retrofit = new Retrofit.Builder()  
            .baseUrl("url")  
            .addConverterFactory(GsonConverterFactory.create())  
            .build();  
  
    ...  
    call.enqueue(new Callback<List<Task>>() {  
        @Override  
        public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {  
            try { 
                List<Task> rs=response.body();
                if(rs.size() > 0){
                    Task user = rs.get(0);
                    String id = user.getId();
                    String location = user.getLocation();
                    Toast.makeText(getApplicationContext(),"Response : Id="+id+" and location="+location, Toast.LENGTH_LONG).show();
                }
                
            }  
            catch (Exception e)  
            {  
                Log.d("REsponse error",e.getMessage());  
            }  
        }  
  
        ... 
    });    
}

并将Task model 更新为

任务.java

public class Task { 
    @SerializedName("id") public String id; 
    @SerializedName("date") public String date; 
    @SerializedName("location") public String location; 
    @SerializedName("img") public String img; 

    public Task(String id, String date, String location, String img) { 
        this.id=id; 
        this.date=date; 
        this.location=location; 
        this.img=img; 
    }

    public String getId(){ return this.id; }
    public String getDate(){ return this.date; }
    public String getLocation(){ return this.location; }
    public String getImg(){ return this.img; }
}

暂无
暂无

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

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