gpt4 book ai didi

java - 如何在 Java 中正确构造 JSON 响应

转载 作者:行者123 更新时间:2023-11-29 05:42:32 25 4
gpt4 key购买 nike

当发送我的 JSON 响应时,我以可见的形式获得了内容类型。这是一个问题,因为当我在另一端解析 JSON 时,它包含 header 并且无法解析回 HashMap 。

我应该如何编码这个响应,这样标题就不会“显示”

这是生成响应的方法

/**
* Sends reply back to client
* @throws Exception
*/
private void sendResponse() throws Exception{

//Content type
String contentTypeLine = "Content-Type: text/json" + "\r\n";

//Create dummy JSON object
HashMap<String, String> mapResponse = new HashMap<String, String>();
mapResponse.put("Author", "James");
mapResponse.put("Author 2", "John");

//Convert to JSON
Gson gson = new Gson();
String json = gson.toJson(mapResponse);

//Set type
responseToClient.writeBytes(contentTypeLine);

//Set JSON
responseToClient.writeBytes(json);

}

这是示例响应

Content-Type: text/json
{"Author":"James","Author 2":"John"}

请求获取代码

/**
* Code to execute on thread
*/
public void run(){

try {

//Log new client
System.out.println("The client " + connectedClient.getInetAddress() +
":" + connectedClient.getPort() + " is connected");

//Get the client request
clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));

//Start response object
responseToClient = new DataOutputStream(connectedClient.getOutputStream());

//Process the request
processClientRequest();

//Close buffered writer
responseToClient.close();
} catch (Exception e) {

//Print error
e.printStackTrace();
}
}

谢谢!

最佳答案

你不需要有这一行:

responseToClient.writeBytes(contentTypeLine);

您只需调用HttpServletResponse#setHeader("Content-type, "application/json")设置适当的内容类型。

关于java - 如何在 Java 中正确构造 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16971964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com