Skip to content

Commit d793db2

Browse files
chore(spring-kafka-test): add mapper
1 parent 7f92186 commit d793db2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.io.example.mapper;
2+
3+
import com.fasterxml.jackson.core.JsonProcessingException;
4+
import com.fasterxml.jackson.databind.ObjectMapper;
5+
import lombok.RequiredArgsConstructor;
6+
import lombok.extern.slf4j.Slf4j;
7+
import org.springframework.stereotype.Component;
8+
9+
@Slf4j
10+
@Component
11+
@RequiredArgsConstructor
12+
public class JsonMapper {
13+
14+
private final ObjectMapper objectMapper;
15+
16+
public String toJsonString(Object obj) {
17+
try {
18+
return objectMapper.writeValueAsString(obj);
19+
} catch (JsonProcessingException e) {
20+
log.error("error converting an object of type {} to json. cause of the error: {}", obj.getClass(), e.getMessage());
21+
throw new RuntimeException("JSON serialization failed", e);
22+
}
23+
}
24+
25+
public <T> T toObject(String jsonBody, Class<T> typeClass){
26+
try {
27+
return objectMapper.readValue(jsonBody, typeClass);
28+
} catch (JsonProcessingException e) {
29+
log.error("error converting an String to object. cause of the error: {}", e.getMessage());
30+
throw new RuntimeException("Object deserialization failed", e);
31+
}
32+
}
33+
34+
}

0 commit comments

Comments
 (0)