-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonMapper.java
More file actions
34 lines (28 loc) · 1.12 KB
/
JsonMapper.java
File metadata and controls
34 lines (28 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.io.example.mapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@RequiredArgsConstructor
public class JsonMapper {
private final ObjectMapper objectMapper;
public String toJsonString(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("error converting an object of type {} to json. cause of the error: {}", obj.getClass(), e.getMessage());
throw new RuntimeException("JSON serialization failed", e);
}
}
public <T> T toObject(String jsonBody, Class<T> typeClass){
try {
return objectMapper.readValue(jsonBody, typeClass);
} catch (JsonProcessingException e) {
log.error("error converting an String to object. cause of the error: {}", e.getMessage());
throw new RuntimeException("Object deserialization failed", e);
}
}
}