end0tknr's kipple - 新web写経開発

http://d.hatena.ne.jp/end0tknr/ から移転しました

jackson for javaによる json → Map<String,Object> map 変換

import java.util.LinkedHashMap;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJson {

    public TestJson() { }

    public static void main(String[] args) {

        String jsonStr =
                "{\"id\":\"1\",\"orders\":["+
                "{\"hinban\":\"H11111\",\"name\":\"商品名A\"},"+
                "{\"hinban\":\"H22222\",\"name\":\"商品名B\"}]}";                
        
        ObjectMapper mapper = new ObjectMapper();
        Map<String,Object> map = new LinkedHashMap<>();
        try {
            map = mapper.readValue(
                    jsonStr,
                    new TypeReference<LinkedHashMap<String,Object>>(){});

        } catch (Exception e) {
            e.printStackTrace();
            return;
        }        
        System.out.println(map.toString());
    }
}

↑こう書くと↓こう表示されるみたい

{id=1, orders=[{hinban=H11111, name=商品名A}, {hinban=H22222, name=商品名B}]}