I'm trying to get a JSON from the body of a request post method (using insomnia/postman), but I have no progress doing this. I did a class called PlayerData, which have only one attribute (userId). I'm using Jackson library to use readValue method, in order to map my json body to my java class PlayerData. To be able to see what is happening, I been have putting a print log and breakpoints to debug what could be, but for some reason, both of them are skipped by my code. I don't return a response, because in this case I don't want to. The idea here is only to set a instance of PlayerData with userId from body request, with no need to persist data on disk.
PlayerData.class
package com.pipa.api;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class PlayerData {
private Integer userId;
}
Application.java
package com.pipa.api;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class Application {
private static ObjectMapper objectMapper;
public static void main(String[] args) throws IOException {
int serverPort = 8000;
HttpServer server = HttpServer.create(new InetSocketAddress(serverPort), 0);
server.createContext("/post", (exchange -> {
if ("POST".equals(exchange.getRequestMethod())) {
PlayerData playerData = objectMapper.readValue(exchange.getRequestBody(), PlayerData.class);
System.out.println("this print never appear");
} else {
exchange.sendResponseHeaders(405, -1); // 405 Method Not Allowed
}
exchange.close();
}));
server.setExecutor(null); // creates a default executor
server.start();
}
}
There are 2 issues with the code.
private static ObjectMapper objectMapper;
is never initialized. Therefore you will get NullPointerException. Tryprivate static ObjectMapper objectMapper = new ObjectMapper();
Using Lombok and Jackson, you may need to make changes as mentioned in this link