import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
// writeValueAsString(value) : value를 String 타입으로 변환
// Map을 json 타입의 String으로 변환
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<>();
map.put("userId", "kang");
map.put("userName", "강호동");
System.out.println("map:" + map);
String jsonStr = (String) mapper.writeValueAsString(map);
System.out.println("jsonStr:" + jsonStr);
// map: {userName=강호동, userId=kang}
// jsonStr: {"userName":"강호동","userId":"kang"}
// readValue( arg, type ) :
// arg: 지정된 타입으로 변환할 대상
// type: 대상을 어떤 타입으로 변환할것인지 클래스를 명시한다. Class객체, TypeReference객체가 올 수 있다.
// json 타입을 Map으로 변환
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<>();
String jsonStr = "{\"userName\" : \"강호동\", \"userId\" : \"kang\"}";
map = mapper.readValue(jsonStr, new TypeReference<Map<String, Object>>() {});
System.out.println("map:" + map);
// List<Map<String, Object>를 Json으로 변환
ObjectMapper mapper = new ObjectMapper();
ArrayList<HashMap<String,Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<>();
map.put("userId", "kang");
map.put("userName", "강호동");
list.add(map);
map = new HashMap<>();
map.put("userId", "hans");
map.put("userName", "한효주");
list.add(map);
System.out.println("list:" + list);
String jsonStr = mapper.writeValueAsString(list);
System.out.println("jsonStr:" + jsonStr);
ArrayList<HashMap<String,Object>> jsonList = new ArrayList<HashMap<String, Object>>();
jsonList = mapper.readValue(jsn, new TypeReference<ArrayList<HashMap<String, Object>>>() {});
System.out.println("jsonList:" + jsonList);
============================================================
data.json
{
"userId" : "kang",
"userName" : "강호동"
}
MyValue.java
package net.programDemo.common.model;
public class MyValue {
public String userId;
public String userName;
}
// file에서 json형식을 읽어서 객체(Class)에 넣어서 사용
String fileName = "data.json";
String filePath = "D:\\uploads\\files\\" + fileName; // 파일이 저장될 위치
System.out.println(filePath);
File file = new File(filePath);
if(file.exists()) {
System.out.println("파일있음");
} else {
System.out.println("파일없음");
}
// ObjectMapper mapper = new ObjectMapper();
MyValue myValue = mapper.readValue(new File(filePath), MyValue.class);
String userId = myValue.userId;
String userName = myValue.userName;
System.out.println("userId:" + userId);
System.out.println("userName:" + userName);
'New Spring' 카테고리의 다른 글
java RESTAPI (0) | 2021.11.17 |
---|---|
ajax json 전송 (0) | 2020.09.16 |
JSON 자바 출력 (json-simple) (0) | 2020.08.30 |