ObjectMapper is the main actor class in the Jackson library. The ObjectMapper class provides the ability to read and write JSON to and from a basic POJO (Plain Old Java Object) or a generic JSON tree model (JsonNode), as well as related functionality for performing conversions.
It also works with both different styles of JSON content and can be highly customized to support more advanced object concepts such as polymorphism and object IDs. ObjectMapper also acts as a factory for the more advanced ObjectReader and ObjectWriter classes.
** * Simply put? ** ** Jackson's ObjectMapper is a class that simplifies Java Objec ↔ Json pershing.
This time, I am creating a chat application using WebSocket, In fact, share the source code of the part you are using.
@Slf4j
@RequiredArgsConstructor
@Service
public class ChatService {
//Declaration
private final ObjectMapper objectMapper;
private Map<String, ChatRoom> chatRooms;
@PostConstruct
private void init() {
chatRooms = new LinkedHashMap<>();
}
public List<ChatRoom> findAllRoom() {
return new ArrayList<>(chatRooms.values());
}
public ChatRoom findRoomById(String roomId) {
return chatRooms.get(roomId);
}
public ChatRoom createRoom(String name) {
String randomId = UUID.randomUUID().toString();
ChatRoom chatRoom = ChatRoom.builder()
.roomId(randomId)
.name(name)
.build();
chatRooms.put(randomId, chatRoom);
return chatRoom;
}
public <T> void sendMessage(WebSocketSession session, T message) {
try {
//Pershing
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
Json will come back normally.
By the way, the following is used in the WebSocket test. Simple WebSocket Clinet
The source code is as follows. https://github.com/twan65/websocket-exam
Recommended Posts