java jsonString convert 유형 정리
2021. 8. 6. 11:00ㆍ개발하는중/java
728x90
반응형
api쪽 개발을 하다보면 json데이터나 다른 파라미터들을 암호화 하기 전이나 평문으로 스트링으로 보내기 위해
컨버트 시켜 주기 위해 작업이 필요 할 떄가 있는데 개발하다가 검색해보며 사용하기 위한 소스를 작성하여 올립니다
만들어 사용하는 VO아니면 Model 을 jsonString로 convert
1
2
3
4
5
|
public static String convertVoToJsonString(SampleVo sampleVo) throws JsonParseException, JsonParseException, IOException{
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(sampleVo);
return jsonString;
}
|
cs |
간단히 map을 jsonString로 convert
1
2
3
4
5
|
public static String convertMapToJsonString(Map<String,Object> pMap) throws JsonParseException, JsonParseException, IOException{
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(pMap);
return jsonString;
}
|
cs |
list를 jsonString로 convert
1
2
3
4
5
|
public static String convertListToJsonString(List<Map<String,Object>> list) throws JsonParseException, JsonParseException, IOException{
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(list);
return jsonString;
}
|
cs |
컨버트하여 전달 했으면 jsonString를 다시 내가 원하는 형태로 담아 사용하기위해 jsonString to convert가 필요 합니다.
jsonString to Map 컨버트 해줍니다
1
2
3
4
5
|
public static HashMap<String, Object> convertJsonToMap(String body) throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> pMap = mapper.readValue(body, new TypeReference<Map<String, Object>>(){});
return pMap;
}
|
cs |
jsonString to list 컨버트 해줍니다.
1
2
3
4
5
|
public static List<Map<?,?>> convertJsonToList(String body) throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
List<Map<?,?>> list = (List) Arrays.asList(mapper.readValue(body, Map[].class));
return list;
}
|
cs |
vo나 model은 map을 로 변경후 셋터로 저장해주면 됩니당
728x90
'개발하는중 > java' 카테고리의 다른 글
json string 중복 value 체크 후 중복 json 제거 (0) | 2023.09.04 |
---|---|
JAVA 입력,출력,연산,swing 사용자UI, 랜덤 기본예제 (0) | 2021.08.27 |
JAVA 입력,출력,변수,연산,랜덤함수, swing입력UI,조건문 기본적인 예제 (0) | 2021.08.27 |
JAVA 입력,출력,변수 기본적인 예제 (0) | 2021.08.26 |
java url통신하여 json파라미터 받아 map으로리턴하기! (0) | 2021.01.21 |