【问题标题】:How to send JSON data as response in nanohttpd如何在 nanohttpd 中发送 JSON 数据作为响应
【发布时间】:2018-05-08 06:22:55
【问题描述】:

我在我的项目中使用nanohttpd 服务器。 GET 请求应该发送一个 JSON 文件作为响应,但 nanohttpd 只允许 String。我该怎么做?

这是 GET 方法:

class GetHandler{
JSONObject response;
JSONObject doGet(Queue queue){
    Map.Entry<String, Message> entry = (Map.Entry<String, Message>)queue.getQueue().entrySet().iterator().next();
    String key = entry.getKey();
    String value = entry.getValue().getText();
    int reCount = entry.getValue().increaseCount();
    queue.getQueue().remove(key);
    Date date = new Date();
    long time = date.getTime();
    queue.getInFlightQueue().put(key,new Message(value, reCount, time));
    System.out.println("ID : " + key + " Message Body : " + value);
    response.put("ID",key);
    response.put("Message Body", value);
    return response;
}
}

这是处理部分:

if (uriComponents[1].equals("queue") && mainHashMap.containsKey(uriComponents[2])) {
    if (mainHashMap.get(uriComponents[2]).getQueue().isEmpty()) {
        response = "Error : trying to access an empty queue";
        return newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, "text/plain", response);
   } else {
        JSONObject message = implementGet.doGet(mainHashMap.get(uriComponents[2]));
        return newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "text/plain", message.toJSONString());
        }
} else {
            response = "Error : Given queue name doesn't exits. Usage:- GET/queue/<queue_name>";
            return newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, "text/plain", response);
}

【问题讨论】:

  • JSON 是一种文本格式,因此您可以对其进行字符串化以在 GET 的响应中设置它(我想,或者如果您需要随请求发送 JSON,请使用 POST)。
  • 我试过了,但它不起作用。当我将其转换为字符串时,GET 请求不会返回任何内容。
  • 你能告诉我们吗?如果没有看到您目前正在做什么,很难提供帮助。使用 edit 添加代码的 sn-p。请参阅How to Ask,如果没有更多信息,我无能为力,这个问题最终会因为过于宽泛而结束。这不是你的第一个问题,你知道它是如何工作的;)
  • 第一件事,我看到你使用text/plain,尝试使用application/json。 (即使这是使用的message.toJSONString(),消息也会知道内容是JSON。那么,这个解决方案的结果是什么?JSON 是否正确'(message.toJSONString() 的结果是什么)。仅供参考:我不知道nanoHTTP,所以这部分留给其他人检查。
  • 两种方法我都试过了,但都不管用。

标签: java json get response nanohttpd


【解决方案1】:

我没有使用 JSON 对象,而是使用了类似 "{\"id\":\"abcd\", \"message\",\"1234\"}" 之类的 JSON 字符串,并且它起作用了。

【讨论】:

  • 更新:我最终使用了 JSON Builder 并将其转换为字符串
猜你喜欢
  • 2019-04-27
  • 2023-03-12
  • 2019-10-09
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多