Jackson

Jackson

Jackson is a Java JSON API which provides several different ways to work with JSON. Jackson is one of the most popular Java JSON APIs out there. You can find Jackson here:

https://github.com/FasterXML/jackson

Jackson contains 2 different JSON parsers:

  • The Jackson ObjectMapper which parses JSON into custom Java objects, or into a Jackson specific tree structure (tree model).
  • The Jackson JsonParser which is Jackson’s JSON pull parser, parsing JSON one token at a time.

Jackson also contains two JSON generators:

  • The Jackson ObjectMapper which can generate JSON from custom Java objects, or from a Jackson specific tree structure (tree model).
  • The Jackson JsonGenerator which can generate JSON one token at a time.

1.0 Jackson Installation

The Java JSON API called Jackson consists of one core JAR file (project) and two other JAR files that use the core JAR file. The three JAR files (projects) in the Jackson JSON API are:

  • Jackson Core
  • Jackson Annotations
  • Jackson Databind

Jackson Gradle Dependencies

compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.3'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.3'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.3'

Git Hub: https://github.com/FasterXML/jackson-core/releases

2.0 Jackson ObjectMapper

How Jackson ObjectMapper Matches JSON Fields to Java Fields

By default Jackson maps the fields of a JSON object to fields in a Java object by matching the names of the JSON field to the getter and setter methods in the Java object. Jackson removes the “get” and “set” part of the names of the getter and setter methods, and converts the first character of the remaining name to lowercase.

package com.zheting.jackson.demo;

public class Car {

    private String brand = null;
    private int doors = 0;

    public Car() {
    }

    public Car(String brand, int doors) {
        this.brand = brand;
        this.doors = doors;
    }

    public String getBrand() {
        return this.brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getDoors() {
        return this.doors;
    }

    public void setDoors(int doors) {
        this.doors = doors;
    }
}
package com.zheting.jackson.demo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author sheting
 */
public class TestObjectMapper{

    /**
     * Read Object From JSON String
     */
    @Test
    public void testJsonToObject() throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();

        //Ignore Unknown JSON Fields
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5, \"color\" : \" black \" }";

        Car car = objectMapper.readValue(carJson, Car.class);

        System.out.println("car brand = " + car.getBrand());
        System.out.println("car doors = " + car.getDoors());
    }

    /**
     * Read Object From JSON Reader
     */
    @Test
    public void testJsonToObject2() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 4 }";
        Reader reader = new StringReader(carJson);

        Car car = objectMapper.readValue(reader, Car.class);

        System.out.println("car brand = " + car.getBrand());
        System.out.println("car doors = " + car.getDoors());
    }

    /**
     * Read Object From JSON File
     */
    @Test
    public void testJsonToObject3() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        File file = new File("src\\main\\resources\\data\\car.json");

        Car car = objectMapper.readValue(file, Car.class);

        System.out.println("car brand = " + car.getBrand());
        System.out.println("car doors = " + car.getDoors());
    }

    /**
     * Read Object From JSON via URL
     */
    @Test
    public void testJsonToObject4() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        //This example uses a file URL, but you can use an HTTP URL too
        URL url = new URL("file:D:\\dev\\learning\\json\\src\\main\\resources\\data\\car.json");

        Car car = objectMapper.readValue(url, Car.class);

        System.out.println("car brand = " + car.getBrand());
        System.out.println("car doors = " + car.getDoors());
    }

    /**
     * Read Object From JSON InputStream
     */
    @Test
    public void testJsonToObject5() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        InputStream input = new FileInputStream("src\\main\\resources\\data\\car.json");

        Car car = objectMapper.readValue(input, Car.class);

        System.out.println("car brand = " + car.getBrand());
        System.out.println("car doors = " + car.getDoors());
    }

    /**
     * Read Object From JSON Byte Array
     */
    @Test
    public void testJsonToObject6() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";

        byte[] bytes = carJson.getBytes(StandardCharsets.UTF_8);

        Car car = objectMapper.readValue(bytes, Car.class);

        System.out.println("car brand = " + car.getBrand());
        System.out.println("car doors = " + car.getDoors());
    }

    /**
     * Read Object Array From JSON Array String
     */
    @Test
    public void testJsonToObject7() throws IOException {
        String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]";

        ObjectMapper objectMapper = new ObjectMapper();

        Car[] cars = objectMapper.readValue(jsonArray, Car[].class);

        System.out.println("car brand = " + cars[0].getBrand());
        System.out.println("car doors = " + cars[0].getDoors());
    }

    /**
     * Read Object List From JSON Array String
     */
    @Test
    public void testJsonToObject8() throws IOException {
        String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]";

        ObjectMapper objectMapper = new ObjectMapper();

        List<Car> cars = objectMapper.readValue(jsonArray, new TypeReference<List<Car>>(){});

        System.out.println("car brand = " + cars.get(0).getBrand());
        System.out.println("car doors = " + cars.get(0).getDoors());
    }


    @Test
    public void testObjectToJson() {
        ObjectMapper objectMapper = new ObjectMapper();

        Car car = new Car("BMW", 4);

        try {
            String json = objectMapper.writeValueAsString(car);
            System.out.println(json);  //{"brand":"BMW","doors":4}
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }


    /**
     *  Jackson has a built-in tree model which can be used to represent a JSON object.
     *  The Jackson tree model is represented by the JsonNode class.
     */
    @Test
    public void testJsonNode(){
        String carJson =
                "{ \"brand\" : \"Mercedes\", \"doors\" : 5," +
                        "  \"owners\" : [\"John\", \"Jack\", \"Jill\"]," +
                        "  \"nestedObject\" : { \"field\" : \"value\" } }";

        ObjectMapper objectMapper = new ObjectMapper();


        try {

            JsonNode node = objectMapper.readValue(carJson, JsonNode.class);

            JsonNode brandNode = node.get("brand");
            String brand = brandNode.asText();
            System.out.println("brand = " + brand);

            JsonNode doorsNode = node.get("doors");
            int doors = doorsNode.asInt();
            System.out.println("doors = " + doors);

            JsonNode array = node.get("owners");
            JsonNode jsonNode = array.get(0);
            String john = jsonNode.asText();
            System.out.println("john  = " + john);

            JsonNode child = node.get("nestedObject");
            JsonNode childField = child.get("field");
            String field = childField.asText();
            System.out.println("field = " + field);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

car.json

{"brand" : "Mercedes", "doors" : 4}

3.0 Jackson JsonParser

The Jackson JsonParser works at a lower level than the Jackson ObjectMapper. This makes the JsonParser faster than the ObjectMapper, but also more cumbersome to work with.

package com.zheting.jackson.demo;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import org.junit.Test;

import java.io.IOException;

/**
 * @author sheting
 */
public class TestJsonParser {

    @Test
    public void testParseJson() throws IOException {

        //Creating a JsonParser
        String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
        JsonFactory factory = new JsonFactory();
        JsonParser parser  = factory.createParser(carJson);

        //Parsing JSON With the JsonParser
        Car car = new Car();
        while(!parser.isClosed()){
            JsonToken jsonToken = parser.nextToken();

            if(JsonToken.FIELD_NAME.equals(jsonToken)){
                String fieldName = parser.getCurrentName();
                System.out.println(fieldName);

                jsonToken = parser.nextToken();

                if("brand".equals(fieldName)){
                    car.setBrand(parser.getValueAsString());
                } else if ("doors".equals(fieldName)){
                   car.setDoors(parser.getValueAsInt());
                }
            }
        }

        System.out.println("car.brand = " + car.getBrand());
        System.out.println("car.doors = " + car.getDoors());
    }

}

4.0 Jackson JsonGenerator

package com.zheting.jackson.demo;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * @author sheting
 */
public class TestJsonGenerator {

    @Test
    public void testGenerateJson() throws IOException {

        //Creating a JsonGenerator
        JsonFactory factory = new JsonFactory();

        JsonGenerator generator = factory.createGenerator(new File("src\\main\\resources\\data\\out_car.json"), JsonEncoding.UTF8);

        //Generating JSON With The JsonGenerator
        generator.writeStartObject();
        generator.writeStringField("brand", "Mercedes");
        generator.writeNumberField("doors", 5);
        generator.writeEndObject();

        //Closing the JsonGenerator
        generator.close();
    }

}

5.0 Jackson Annotations

Read + Write Annotations

  • @JsonIgnore
    The Jackson annotation @JsonIgnore is used to tell Jackson to ignore a certain property (field) of a Java object. The property is ignored both when reading JSON into Java objects, and when writing Java objects into JSON.

  • @JsonIgnoreProperties
    The @JsonIgnoreProperties Jackson annotation is used to specify a list of properties of a class to ignore. The @JsonIgnoreProperties annotation is placed above the class declaration instead of above the individual properties (fields) to ignore.

  • @JsonIgnoreType
    The @JsonIgnoreType Jackson annotation is used to mark a whole type (class) to be ignored everywhere that type is used.

  • @JsonAutoDetect
    The Jackson annotation @JsonAutoDetect is used to tell Jackson to include properties which are not public, both when reading and writing objects.
    The JsonAutoDetect.Visibility class contains constants matching the visibility levels in Java, meaning ANY, DEFAULT, NON_PRIVATE, NONE, PROTECTED_AND_PRIVATE and PUBLIC_ONLY.

Read Annotations

Jackson contains a set of annotations that only affect how Jackson parses JSON into objects - meaning they affect Jackson’s reading of JSON. I refer to these as “read annotations”. The following sections explains Jackson’s read annotations.

  • @JsonSetter
    The Jackson annotation @JsonSetter is used to tell Jackson that is should match the name of this setter method to a property name in the JSON data, when reading JSON into objects. This is useful if the property names used internally in your Java class is not the same as the property name used in the JSON file.

Write Annotations

Jackson also contains a set of annotations that can influence how Jackson serializes (writes) Java objects to JSON. Each of these write (serialization) annotations will be covered in the following sections.

  • @JsonInclude
    The Jackson annotation @JsonInclude tells Jackson only to include properties under certain circumstances. For instance, that properties should only be included if they are non-null, non-empty, or have non-default values.

  • @JsonGetter
    The @JsonGetter Jackson annotation is used to tell Jackson that a certain field value should be obtained from calling a getter method instead of via direct field access. The @JsonGetter annotation is useful if your Java class uses jQuery style for getter and setter names.

  • @JsonPropertyOrder
    The @JsonPropertyOrder Jackson annotation can be used to specify in what order the fields of your Java object should be serialized into JSON.

  • @JsonRawValue
    The @JsonRawValue Jackson annotation tells Jackson that this property value should written directly as it is to the JSON output.

  
  
reference :http://tutorials.jenkov.com/java-json/index.html

發佈了78 篇原創文章 · 獲贊 42 · 訪問量 53萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章