Как я должен вернуть значение JSON в другой метод - PullRequest
0 голосов
/ 23 сентября 2019

Я получаю ответ JSON от API.Я должен вернуть ответ 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 другому методу для вставки в базу данных.

Ответы [ 2 ]

0 голосов
/ 23 сентября 2019

Просто измените тип параметра метода insertdb на String, а затем проанализируйте его в JSONObject в вашем методе.

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

public void insertdb(String jsonString) throws Exception{
// parse object
JSONObject json = JSONObject.parseObject(jsonString);

Connection con = ConnectToDB(); 
String tablename="Cluster_Info";
JSONObject cluster = new JSONObject(json); 
System.out.println(cluster);
JSONArray array=cluster.getJSONArray("clusters");
0 голосов
/ 23 сентября 2019
  • используйте gson-2.1.jar или более позднюю версию.
  • просто создайте POJO (сбор) с полями идентификатора и времени (с получателем / установщиком)

  • Добавьте еще один класс с элементами списка, как показано ниже

    public class GatherDetails{private List<Gather> items;}
    
  • Добавьте приведенную ниже строку преобразования в основной 1-й метод.

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

Теперь у collectDetails есть список объектов. Отредактируйте второй метод, как показано ниже.

public void insertdb(GatherDetails gatherDetails) throws Exception{
for(Gather gather:GatherDetails.items){
gather.getId();gather.getTime();
//insert logic goes here
}}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...