전체/Java
Jackson JSON 라이브러리 mapper.readTree 사용하기, Iterator 이용하기
effortDev
2017. 9. 14. 16:02
Jackson JSON 라이브러리 mapper.readTree 사용하기
JsonNode myJsonNode = mapper.readTree(myJson); // String myJson값을 Json형태로 바꿔서
Iterator itr = myJsonNode2.getElements(); // Iterator를 사용해 요소를 객체로 저장한다.
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 40 41 42 43 44 45 46 47 | import java.io.IOException; import java.util.Iterator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; public class JacksonTest { public static void main(String[] args) throws JsonProcessingException, IOException { ObjectMapper mapper = new ObjectMapper(); String myJson = "{\"a\":1990, \"b\":\"b is string\", \"c\": [{\"d1\":\"d1 is string\"}, {\"d2\":\"d2 is string\"}]}"; myJson1(mapper, myJson); myJson2(mapper, myJson); } // 1. mapper.readTree 사용하기 private static void myJson1(ObjectMapper mapper, String myJson) throws JsonProcessingException, IOException { JsonNode myJsonNode = mapper.readTree(myJson); System.out.println("myJsonNode1:"+myJsonNode); // myJsonNode1:{"a":1990,"b":"b is string","c":[{"d1":"d1 is string"},{"d2":"d2 is string"}]} if (myJsonNode.isObject()) { ObjectNode obj = (ObjectNode) myJsonNode; if (obj.has("c")) { JsonNode valueC= obj.get("c").get(0).get("d1"); System.out.println("valueC Text값: "+valueC.getTextValue()); // valueC Text값: d1 is string } } } // 2. mapper.readTree와 Iterator 사용하기 private static void myJson2(ObjectMapper mapper, String myJson) throws JsonProcessingException, IOException { JsonNode myJsonNode2 = mapper.readTree(myJson); System.out.println("myJsonNode2:"+myJsonNode2); // myJsonNode2:{"a":1990,"b":"b is string","c":[{"d1":"d1 is string"},{"d2":"d2 is string"}]} Iterator itr = myJsonNode2.getElements(); while( itr.hasNext()) { JsonNode obj = (JsonNode)itr.next(); System.out.println(obj); } } } | cs |
[출력 결과]
myJsonNode1:{"a":1990,"b":"b is string","c":[{"d1":"d1 is string"},{"d2":"d2 is string"}]}
valueC Text값: d1 is string
myJsonNode2:{"a":1990,"b":"b is string","c":[{"d1":"d1 is string"},{"d2":"d2 is string"}]}
1990
"b is string"
[{"d1":"d1 is string"},{"d2":"d2 is string"}]