728x90
반응형
java obj --> jsonString, jsonString --> JSONObject
- 주의사항 : 객체 getter 가 구현되있어야 함.
/**
* java object --> jsonObject string
* 객체안의 객체도 표현 가능
* @warnings 주의사항으로는 java object getter 가 구현되있어야 함.
* @param object
* @return
*/
public static String getJsonStringFromJavaObj(Object object) {
if (ObjectUtils.isEmpty(object)) {
log.error("object is empty. object : {}", object);
throw new IllegalArgumentException(String.format("object is empty. object : %s", object));
}
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(object);
} catch (Throwable th) {
log.error(th.getMessage(), th);
throw new RuntimeException(th);
}
}
/**
* json string --> JSONObject 변환
* @param jsonString
* @return
*/
public static JSONObject getJSONObjectFromJsonString(String jsonString) {
if (StringUtils.isEmpty(jsonString)) {
log.error("jsonString is empty");
throw new IllegalArgumentException("jsonString is empty.");
}
try {
JSONParser parser = new JSONParser();
return (JSONObject) parser.parse(jsonString);
} catch (Throwable th) {
log.error(th.getMessage(), th);
throw new RuntimeException(th);
}
}
// test
@Test
public void getJsonStringFromJavaObjectTest() throws Exception {
String jsonStr = JsonUtils.getJsonStringFromJavaObj(new Member("test", 10, new Address("test address")));
Assert.assertNotNull(jsonStr);
}
@Test
public void getJSONObjectFromJsonStringTest() throws Exception {
String jsonString = JsonUtils.getJsonStringFromJavaObj(new Member("test", 10, new Address("test address")));
JSONObject jsonObject = JsonUtils.getJSONObjectFromJsonString(jsonString);
Assert.assertThat(jsonObject.get("name"), is("test"));
Assert.assertThat(jsonObject.get("age"), is(10L));
}
static class Member {
private String name;
private int age;
private Address address;
public Member(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Address getAddress() {
return address;
}
}
static class Address {
private String addr;
public Address(String addr) {
this.addr = addr;
}
public String getAddr() {
return addr;
}
}
'Java' 카테고리의 다른 글
java main args 에 json parameter 넘기는 방법 (0) | 2021.02.06 |
---|---|
apache webserver error page customize (0) | 2021.01.24 |
jsonarray to listmap 변환 (0) | 2021.01.17 |
java jsonObject to map (json-simple, jackson 사용) (0) | 2021.01.15 |
java bigdecimal 나누기 소수점 계산 주의사항 (0) | 2021.01.09 |
댓글