[JAVA] ObjectMapper class

What is ObjectMapper?

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.

I tried using it!

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);
        }
    }
}

result

image.png

Json will come back normally.

Recommended Posts

ObjectMapper class
11th class: Class
Anonymous class (anonymous class)
Class method
ArrayList class
JDBC class load
Java class methods
Class and model
9th class: assert_equal
java Scanner class
Decompile class files
Java HashMap class
10th class: Recursion
About class inheritance.
java (abstract class)
Class in Ruby
[Java] Nested class
Java anonymous class
About Java class
8th class: rake
String class methods
[Week 11] class, ruby_sixth
java.lang.IncompatibleClassChangeError: Implementing class
[java] abstract class
[Java] Object class
Java local class
5th class: Output
Impl class Vo class
WildFly class loading