본문

JSON-String to Map(JAVA)

반응형

1. Convert JSON-String To Map


Source) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.source.json_string;
 
import java.util.HashMap;
import java.util.Map;
 
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
 
public class Main {
    public static void main(String[] args) throws Exception {
        
        Map<String, Object> dataMap = new HashMap<String, Object>();
 
        // {"name":"person","phone":"000-0000-0000","age":"10"}
        String json = 
                "{\"" + "name\":\"person" + "\"" + ","
                + "\"" + "phone\":\"000-0000-0000" + "\"" + ","
                + "\"" + "age\":\"10" + "\"}";
        
        System.out.println("JSON String : " + json);
 
        dataMap = convertJSONstringToMap(json);
        
        System.out.println("convertJSONstringToMap : " + dataMap);
        
        
    }
    
    public static Map<String,Object> convertJSONstringToMap(String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = new HashMap<String, Object>();
        
        map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
        
        return map;
    }
}
 
 
cs

Result)
1
2
3
JSON String : {"name":"person","phone":"000-0000-0000","age":"10"}
convertJSONstringToMap : {name=person, phone=000-0000-0000, age=10}
 
cs

Dependency)

1
2
3
4
5
<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-lgpl</artifactId> 
    <version>1.3.0</version>
</dependency>
cs



P.S.) javascript에서 JSONstring 사용시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var data = {
    name    : "person",
    phone   : "000-0000-0000",
    age     : "10"
};
 
var jsonStringData = JSON.stringify(data);
 
// TODO : 변수 jsonStringData에 담긴 데이터, ajax를 이용하여 Controller영역으로 넘겨 사용
// Controller영역에서는 String Type으로 jsonStringData를 받아
// 위의 로직과 동일하게 
// map = mapper.readValue(jsonStringData, new TypeReference<Map<String, Object>>() {});
// 형식으로 사용
 
cs


2. Convert JSON-Array-String To Map


Source) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.Map;
import net.sf.json.JSONArray;
 
public class Test {
 
    public static void main(String[] args) {
        
        String jsonStr = "[{\"DATA_KEY1\":\"0.018\",\"DATA_KEY2\":\"0.017\"}]";
        
        // jsonStr: [{"DATA_KEY1":"0.018","DATA_KEY2":"0.017"}]
        System.out.println("jsonStr: " + jsonStr);
        
        JSONArray jsonArr = JSONArray.fromObject(jsonStr);
        Map jsonMap = (Map<String, Object>) jsonArr.toArray()[0];
 
        // DATA_KEY1: 0.018
        System.out.println("DATA_KEY1: " + jsonMap.get("DATA_KEY1"));
    }
 
}
 
 


반응형

공유

댓글