Jacksonを使用してJavaでJSONを処理する


仕事で実際にJava処理JSONを使っている場合が多く,オープンソースツールJacksonで実現されていることが多い.
一.入門
        Jacksonには、JavaオブジェクトとJSONの交換に使用されるObjectMapperクラスがあります.
1.JavaオブジェクトをJSONに変換
Student st=new Student(); //Java Object
ObjectMapper mapper = new ObjectMapper();
java.text.DateFormat myFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.getSerializationConfig().setDateFormat(myFormat);
try {
    //     
    String res = mapper.writeValueAsString(st);
    System.out.println(res);
    
    //          (     )
    res = mapper.defaultPrettyPrintingWriter().writeValueAsString(st);
    System.out.println(res);
    
    mapper.writeValue(new File("D:\\st.json"), st); //      
     
    //       (  ),           .
    mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
    
    res = mapper.writeValueAsString(st);
    System.out.println(res);
} catch (Exception e) {
    e.printStackTrace();
}

 
2.JSON逆シーケンス化Javaオブジェクト
String json = "{\"error\":0,\"data\":{\"name\":\"ABC\",\"age\":20,\"phone\":{\"home\":\"abc\",\"mobile\":\"def\"},\"friends\":[{\"name\":\"DEF\",\"phone\":{\"home\":\"hij\",\"mobile\":\"klm\"}},{\"name\":\"GHI\",\"phone\":{\"home\":\"nop\",\"mobile\":\"qrs\"}}]},\"other\":{\"nickname\":[]}}";
ObjectMapper mapper = new ObjectMapper();
//          
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
//          
mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
try {
    //   HashMap  
    HashMap jsonMap = mapper.readValue(json, HashMap.class);
    Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
    System.out.println(maps.get("error"));//0
    System.out.println((Object) (maps.get("data").get("phone")));//{home=abc, mobile=def}
} catch (Exception e) {
    e.printStackTrace();
}

 
二.Jacksonは三つの使用方法をサポートする
1.Data Binding:最も使いやすい
(1)Full Data Binding
/*
 * Full Data Binding
 */
public static void fullDataBinding() {

    ObjectMapper mapper = new ObjectMapper();
    try {
        Model model = mapper.readValue(MODEL_BINDING, Model.class);
        //readValue       .  
        System.out.println(model.getName()); //name1 
        System.out.println(model.getType()); //1
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static class Model {
    private String name;
    private int type;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}

 
(2)Raw Data Binding
/*
 * Raw Data Binding
 */
public static void rawDataBinding() {
    ObjectMapper mapper = new ObjectMapper();
    try {
        HashMap map = mapper.readValue(MODEL_BINDING, HashMap.class);//readValue         .  
        System.out.println(map.get("name")); //name1
        System.out.println(map.get("type")); //1
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 
(3)generic Data Binding
/*
 * generic Data Binding
 */
public static void genericDataBinding() {
    
    ObjectMapper mapper = new ObjectMapper();
    try {
        HashMap<String, Model> modelMap = mapper.readValue(GENERIC_BINDING,
                new TypeReference<HashMap<String, Model>>() {
                });//readValue        .  
        Model model = modelMap.get("key2");
        System.out.println(model.getName()); //name3
        System.out.println(model.getType()); //3
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 
2.Tree Model:最も柔軟
/*
 * Tree Model:   
 */
public static void treeModelBinding() {
    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);
        //path get    ,            ,  missing node   Null.  
        String treekey2value = rootNode.path("treekey2").getTextValue();//  
        System.out.println("treekey2value:" + treekey2value);
        JsonNode childrenNode = rootNode.path("children");
        String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();
        System.out.println("childkey1Value:" + childkey1Value);

        //       
        ObjectNode root = mapper.createObjectNode();
        //     1  
        ObjectNode node1 = mapper.createObjectNode();
        node1.put("nodekey1", 1);
        node1.put("nodekey2", 2);
        //     1  
        root.put("child", node1);
        //      
        ArrayNode arrayNode = mapper.createArrayNode();
        arrayNode.add(node1);
        arrayNode.add(1);
        //        
        root.put("arraynode", arrayNode);
        //JSON       
        JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);
        //  JSON    
        root.put("valuetotreenode", valueToTreeNode);
        //JSON   JSON      
        JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//  JSON JSON    .  
        //  JSON    
        root.put("bindJsonNode", bindJsonNode);
        System.out.println(mapper.writeValueAsString(root));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 
3.Streaming API.最適なパフォーマンス
公式文書の例を参照してください.
 
さらに学習資料:
1.http://wiki.fasterxml.com/JacksonInFiveMinutes Jackson公式チュートリアルの例
2.http://wiki.fasterxml.com/JacksonJavaDocs JacksonオンラインAPIドキュメント
3.http://hjg1988.iteye.com/blog/561368 JSONツールのパフォーマンス比較:json-libとjacksonはJavaオブジェクトからjson文字列へのシーケンス化を行います.
 
記事の出典:http://shensy.iteye.com/blog/1717776