Jackson Treeモデルの例
ジャクソンでは、 “Tree Model”を使ってJSONを表現し、 “JsonNode”を使って読み書き操作を実行できます。これはXML DOMツリーに似ています。
P.S Jackson 2.6.3
でテスト済み
1. TreeModelのトラバースの例
1.1 JSONファイル、トップレベルはオブジェクトを表します。
c:\\ user.json
{ "id" : 1, "name" : { "first" : "Yong", "last" : "Mook Kim" }, "contact" :[ { "type" : "phone/home", "ref" : "111-111-1234"}, { "type" : "phone/work", "ref" : "222-222-2222"} ]}
1.2 Jackson TreeModel(
JsonNode
)を使用して、JSONファイルを解析して走査します。コメントは読んでください。
JacksonTreeModel.java
package com.mkyong.json; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTreeModel { public static void main(String[]args) { try { long id; String firstName = ""; String middleName = ""; String lastName = ""; ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(new File("c:\\user.json")); //Get id id = root.path("id").asLong(); System.out.println("id : " + id); //Get Name JsonNode nameNode = root.path("name"); if (nameNode.isMissingNode()) { //if "name" node is missing } else { firstName = nameNode.path("first").asText(); //missing node, just return empty string middleName = nameNode.path("middle").asText(); lastName = nameNode.path("last").asText(); System.out.println("firstName : " + firstName); System.out.println("middleName : " + middleName); System.out.println("lastName : " + lastName); } //Get Contact JsonNode contactNode = root.path("contact"); if (contactNode.isArray()) { //If this node an Arrray? } for (JsonNode node : contactNode) { String type = node.path("type").asText(); String ref = node.path("ref").asText(); System.out.println("type : " + type); System.out.println("ref : " + ref); } } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
出力
id : 1 firstName : Yong middleName : lastName : Mook Kim type : phone/home ref : 111-111-1234 type : phone/work ref : 222-222-2222
2. TreeModelのトラバースの例 – 第2部
2.1 JSONファイル、トップレベルは配列を表します。
c:\\ user2.json
….[ {
“id” : 1,
“name” : {
“first” : “Yong”,
“last” : “Mook Kim”
},
“contact” :[ { “type” : “phone/home”, “ref” : “111-111-1234”},
{ “type” : “phone/work”, “ref” : “222-222-2222”}
]},
{
“id” : 2,
“name” : {
“first” : “Yong”,
“last” : “Zi Lap”
},
“contact” :[ { “type” : “phone/home”, “ref” : “333-333-1234”},
{ “type” : “phone/work”, “ref” : “444-444-4444”}
]}]….
2.2概念は同じで、最初のノードをループするだけです。
ObjectMapper mapper = new ObjectMapper(); JsonNode rootArray = mapper.readTree(new File("c:\\user2.json")); for(JsonNode root : rootArray){ //refer example 1.2 above, same ways to process nodes }
3. TreeModelのCRUDの例
3.1この例題では、ノード(
ObjectNode`と
ArrayNode`)を作成、更新、削除する方法を示します。コメントを読み、自明です。
JacksonTreeModel.java
package com.mkyong.json; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class JacksonTreeModel { public static void main(String[]args) { try { ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(new File("c:\\user.json")); String resultOriginal = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root); System.out.println("Before Update " + resultOriginal); //1. Update id to 1000 ((ObjectNode) root).put("id", 1000L); //2. If middle name is empty , update to M JsonNode nameNode = root.path("name"); if ("".equals(nameNode.path("middle").asText())) { ((ObjectNode) nameNode).put("middle", "M"); } //3. Create a new field in nameNode ((ObjectNode) nameNode).put("nickname", "mkyong"); //4. Remove last field in nameNode ((ObjectNode) nameNode).remove("last"); //5. Create a new ObjectNode and add to root ObjectNode positionNode = mapper.createObjectNode(); positionNode.put("name", "Developer"); positionNode.put("years", 10); ((ObjectNode) root).set("position", positionNode); //6. Create a new ArrayNode and add to root ArrayNode gamesNode = mapper.createArrayNode(); ObjectNode game1 = mapper.createObjectNode(); game1.put("name", "Fall Out 4"); game1.put("price", 49.9); ObjectNode game2 = mapper.createObjectNode(); game2.put("name", "Dark Soul 3"); game2.put("price", 59.9); gamesNode.add(game1); gamesNode.add(game2); ((ObjectNode) root).set("games", gamesNode); //7. Append a new Node to ArrayNode ObjectNode email = mapper.createObjectNode(); email.put("type", "email"); email.put("ref", "[email protected]"); JsonNode contactNode = root.path("contact"); ((ArrayNode) contactNode).add(email); String resultUpdate = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root); System.out.println("After Update " + resultUpdate); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
出力
Before Update { "id" : 1, "name" : { "first" : "Yong", "last" : "Mook Kim" }, "contact" :[{ "type" : "phone/home", "ref" : "111-111-1234" }, { "type" : "phone/work", "ref" : "222-222-2222" }]} After Update { "id" : 1000, "name" : { "first" : "Yong", "middle" : "M", "nickname" : "mkyong" }, "contact" :[{ "type" : "phone/home", "ref" : "111-111-1234" }, { "type" : "phone/work", "ref" : "222-222-2222" }, { "type" : "email", "ref" : "[email protected]" }], "position" : { "name" : "Developer", "years" : 10 }, "games" :[{ "name" : "Fall Out 4", "price" : 49.9 }, { "name" : "Dark Soul 3", "price" : 59.9 }]}
参考文献
ジャクソンによる処理:方法#3/3:ツリートラバーサル]。
http://stackoverflow.com/questions/23271699/adding-property-to-json-using-jackson
[StackOverflow
: Adding property to JSON using Jackson]. link://java/jackson-2-convert-java-object-to-from-json/[Jackson 2 –
JSONとオブジェクトの変換]