繁体   English   中英

如何在nanohttpd中将JSON数据作为响应发送

[英]How to send JSON data as response in nanohttpd

我在我的项目中使用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对象,而是使用了类似"{\\"id\\":\\"abcd\\", \\"message\\",\\"1234\\"}"的JSON字符串"{\\"id\\":\\"abcd\\", \\"message\\",\\"1234\\"}"并且它有效。

暂无
暂无

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

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