java - 我应该如何将 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 响应发送到其他方法以插入数据库。
解决方案
- 使用 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
}}
推荐阅读
- php - 访问多维数组中的第一个索引并将其与数字进行比较
- deep-learning - HUGGINGFACE TypeError:“NoneType”和“int”实例之间不支持“>”
- ios - 关闭呈现的视图控制器时如何恢复焦点?
- c# - 在 WebAPI 中解析 Unicode 参数值
- javascript - 在 JavaScript 中从数组中删除一个项目
- javascript - NextJS 如何从公共构建中删除 getServerSideProps
- javascript - 嵌套 If 条件中的良好实践
- c - 栈的动态内存分配数组
- java - Tomcat 上的 Java Spring MVC 应用程序给出错误 404
- r - 如何在R中的同一数据框中逐行查找共同元素