首页 > 解决方案 > 我应该如何将 json 值返回到另一个方法中

问题描述

我正在从 API 获取 JSON 响应。我应该将这些 JSON 响应返回给另一种方法。

    HttpClient client = HttpClientBuilder.create().build(); 
    HttpGet request=new HttpGet("/2.0/clusters/list");
    request.addHeader("Authorization",bearerToken); 
    request.addHeader("cache-control", "no-cache"); 
    HttpResponse response=client.execute(request); 
    System.out.println("Response Code:" +   
    response.getStatusLine().getStatusCode());
    String json = EntityUtils.toString(response.getEntity());
    System.out.println("Gather Details\n"); 
    JSONObject cluster = new JSONObject(json); 
    JSONArray array=cluster.getJSONArray("clusters");
    for (int i=0;i< array.length();i++)
    {
    JSONObject clusters = array.getJSONObject(i); 
    String id=clusters.get("id").toString(); 
    String time=clusters.get("time").toString();
    System.out.println("Id:"+id+"time:"+time+"\n");

    if(response.getStatusLine().getStatusCode()!=200) {
    System.out.println("Failed HTTP 
    response"+response.getStatusLine().getStatusCode()+" "+json);
              }
    return json;

/*Another method which takes json values and insert into db*/

    public void insertdb(JSONObject json) throws Exception{
    Connection con = ConnectToDB(); 
    String tablename="Cluster_Info";
    JSONObject cluster = new JSONObject(json); 
    System.out.println(cluster);
    JSONArray array=cluster.getJSONArray("clusters");

帮助我将 json 响应发送到其他方法以插入数据库。

标签: javaarraysjsonobject

解决方案


  • 使用 gson-2.1.jar 或更高版本。
  • 只需使用 ID 和时间字段(使用 getter/setter)创建 POJO(Gather)

  • 添加另一个具有列表项的类,如下所示

    public class GatherDetails{private List<Gather> items;}
    
  • 在 main 1'st 方法中添加以下转换行。

    HttpResponse response=client.execute(request);
    Gson gson = new Gson();
    GatherDetails gatherDetails= gson.fromJson(response.getEntity(), GatherDetails.class);
    

现在gatherDetails 有一个对象列表。像下面这样编辑第二种方法。

public void insertdb(GatherDetails gatherDetails) throws Exception{
for(Gather gather:GatherDetails.items){
gather.getId();gather.getTime();
//insert logic goes here
}}

推荐阅读