简体   繁体   English

如何使用 Java 检查 JSON 响应是否返回 [] 或带有正文的响应?

[英]How to check if JSON respone returns [ ] or response with body using Java?

I have an API that hits multiple times for different Event IDs.我有一个 API,它针对不同的事件 ID 多次命中。
Few have date and few does not.很少有约会,也很少有人没有。 I get this error:我收到此错误:

Premature end of chunk coded message body: closing chunk expected块编码消息体过早结束:预期关闭块

Here is my code :这是我的代码:

CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("my API URL");

System.out.println("request:"+request.getURI());
String list = request.getURI().toString();

request.addHeader("Authorization",bearerToken); // Adding the bearer token
request.addHeader("Content-Type", "application/json");

CloseableHttpResponse response = client.execute(request);

//try
//{
    System.out.println(response.getStatusLine());
    System.out.println(response.getEntity().getContentLength());

    HttpEntity ent = response.getEntity();

    if(ent!=null)
    {
        //InputStream in = new PushbackInputStream(ent.getContent());
        //in = new ByteArrayInputStream(EntityUtils.toByteArray(ent));
        EntityUtils.consume(ent);
        System.out.println(response.getEntity());
        //in.close();
    }

Can someone tell me where I am going wrong or how are we suppose to do this?有人能告诉我我哪里出错了,或者我们应该怎么做?

If my response does not have data, I need to just print them and go to next Event ID and check.如果我的响应没有数据,我只需要打印它们并转到下一个事件 ID 并检查。
Some of my API returns just [ ].我的一些 API 只返回 []。 Very new to Java as well. Java 也很新。

When you use json libraries, they usually have some methods to check weather the json object is empty or not.当你使用 json 库时,它们通常有一些方法来检查 json 对象是否为空。 you can use them in your code, for example in JSONObject we have isEmpty() method which returns a boolean and it is what you need.您可以在代码中使用它们,例如在 JSONObject 中,我们有 isEmpty() 方法,它返回一个布尔值,这正是您所需要的。

besides if your problem is just one of the conditional of the answers just put it in your "if condition" after checking not to being null, for example:此外,如果您的问题只是答案的条件之一,请在检查不为空后将其放入“if 条件”中,例如:

if (string != null || !string.equals("[]")) {
    // your code 
}

but this is not a general way and in this way your code is not compatible with all kinds of the answers.但这不是通用方法,因此您的代码与所有类型的答案都不兼容。

Have you tried checking if the json object length is zero?您是否尝试过检查 json 对象长度是否为零?

eg.例如。

if(ent.length == 0){
    //Do thing
}

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

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