Android에서 Object 또는 List 와 JSON 간에 변환
1. build.gradle 에 추가
implementation 'com.fasterxml.jackson.core:jackson-core:2.9.7'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.9.7'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.7'
2. Object 또는 List<Object> → JSON
List<Model> webSiteModels = handler.selectModelList(ModelType.WEB_SITE);
ObjectMapper mapper = new ObjectMapper();
try {
//파일로 저장
mapper.writeValue(new File("c:\\test.json"), webSiteModels);
//문자열로 변환
String webSiteJsonString = mapper.writeValueAsString(webSiteModels);
}
catch (Exception e) {
e.printStackTrace();
}
3. JSON → Object 또는 JSON → List<Object>
- 단일 Object인 경우
String webSiteContentsString = "{'account': 'ibluenet'}";
Model convertWebSiteModel = mapper.readValue(webSiteContentsString, Model.class);
- List 인 경우
String webSiteContentsString = "[{'account': 'ibluenet'},{'account': 'redman'}]";
List<Model> convertWebSiteModels = mapper.readValue(webSiteContentsString, new TypeReference<List<Model>>(){});