При отправке моего ответа JSON я получаю вид в виде содержимого. Это проблема, потому что когда я разбираю JSON с другой стороны, он включает заголовки, и он не может проанализировать обратно в хэш-карту.Как правильно структурировать ответ JSON в Java
Как я должен кодировать этот ответ так, что заголовки не «шоу»
Вот метод, который генерирует ответ
/**
* 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();
}
}
Спасибо!
Вы можете просто пойти по строкам и сделать простой if (line.contains ("{")), то // сделать что-то – shaunw