본문 바로가기
  • AI (Artificial Intelligence)
Programming/Java

Jackson Tutorial - 1

by 로샤스 2014. 9. 11.
  1. Jackson tutorial(http://wiki.fasterxml.com/JacksonInFiveMinutes)
  2. 차례
    • JSON Three Ways
    • Examples
      • Full Data Binding (POJO) Example
      • Simple Data Binding Example
      • Data Binding with Generics
      • Three Model Example
      • Streaming API Example

     

  3. JSON Three Ways
    • Jackson JSON 데이터를 처리하기 위한 세가지 방법을 제공한다.
    • Streaming API(aka Incremental Processing, or Token Streams)
      • http://wiki.fasterxml.com/JacksonStreamingApi
      • Streaming API JSON 데이터를 처리하는데 가장 효과적인 방법이다.
      • 어플리케이션 보다는 주로 미들웨어나 프레임워크와 같이 성능이 중요한 곳에서 사용된다.
      • 장점 : Lowest memory and processing overhead
      • 단점
        • 모든 데이터는 순차적으로 처리된다. Random Access 불가.
        • 매우 기본적인 데이터 타입만 제공한다.(String, byte[] for base64-encoded binary content)
      • org.codehaus.jackson.JsonParser reads, org.codehaus.jackson.JsonGenerator writes.
        • Creating Parsers
          • Paraser JSON Content에서 각각의 데이터를 분리한다.
          • JSON Content 대한 Low-level access.
          • org.codehaus.jackson.JsonFactory has extensive set of methods to construct parsers
          • Example

    JsonFactory jsonFactory = new JsonFactory();

                        // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory

    JsonParser jp = jsonFactory.createJsonParser(file); // or URL, Stream, Reader, String, byte[]

    • Creating Generators
      • JSON Cotent JSON 각각의 데이터로 분리해준다.
      • Example

    JsonFactory jsonFactory = new JsonFactory();

                              // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory

    JsonGenerator jg = jsonFactory.createJsonGenerator(file, JsonEncoding.UTF8); // or Stream, Reader

      <<첫번째 방법>>

     // general method, same as with data binding

      ObjectMapper mapper = new ObjectMapper();

      // (note: can also use more specific type, like ArrayNode or ObjectNode!)

      JsonNode rootNode = mapper.readValue(src, JsonNode.class); // src can be a File, URL, InputStream etc

     

      <<두번째 방법>>

      // or, with dedicated method; requires a JsonParser instance

      JsonParser jp = ...; // construct using JsonFactory (can get one using ObjectMapper.getJsonFactory)

      rootNode = mapper.readTree(jp);

      // (most useful when binding sub-trees)

     

    • Constructing Tree Model instances from Scratch

      ObjectMapper mapper = new ObjectMapper();

      JsonNode rootNode = mapper.createObjectNode(); // will be of type ObjectNode

      ((ObjectNode) rootNode).put("name", "Tatu");

      // ... and so forth

    • Writing Trees as JSON

    mapper.writeValue(dst, myBean); // dst can be File, OutputStream, Writer etc

    • Converting to Token Stream

      JsonParser jp = node.traverse();

      // or:

      JsonParser jp = mapper.treeAsTokens(node);

    • Converting to Java Objects

    MyBean bean = mapper.treeToValue(node, MyBean.class);

     

    • Data Binding
      • http://wiki.fasterxml.com/JacksonDataBinding
      • converts JSON to and from POJOs based either on property accessor conventions or annotations.
      • 가지 방법
        • Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls
        • Full data binding means converting to and from any Java bean type (as well as "simple" types mentioned above)
      • org.codehaus.jackson.map.ObjectMapper performs the marshalling and unmarshalling for both variants.
      • Serialization

    ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(dst, myBean); // where 'dst' can be File, OutputStream or Writer

    • Full Data Binding

    MyBean value = mapper.readValue(src, MyBean.class); // 'src' can be File, InputStream, Reader, String

     

    • Generic Types: TypeReference Object 사용한다.

    MyType<String> genValue = mapper.readValue(src, new TypeReference<MyType<String>>() { });

    • "Simple" Data Binding

    Object root = mapper.readValue(src, Object.class);

    Map<?,?> rootAsMap = mapper.readValue(src, Map.class);

     

    • 사용 가능한 Type

    JSON Type

    Java Type

    object

    LinkedHashMap<String,Object>

    array

    ArrayList<Object>

    string

    String

    number (no fraction)

    Integer, Long or BigInteger (smallest applicable)

    number (fraction)

    Double (configurable to use BigDecimal)

    true|false

    Boolean

    null

    null

     

    • Configuring
      • SerializationConfig.Feature
      • DeserializationConfig.Feature

     

    • 정리하면,
      • Streaming API 성능이 가장 좋고, Data Binding 가장 사용하기 편하며, Tree Model 가장 유연하다.
      • 특별한 사유가 아니라면 Data Binding 쓰겠지?;;;





















출처 : http://youreme.blog.me/110082668135






















댓글