精华内容
下载资源
问答
  • ObjectMapper

    2021-03-04 15:22:46
    ObjectMapper可以将java对象和json字符串相互转换 ObjectMapper mapper = new ObjectMapper(); Object readValue = mapper.readValue(json, Object.class);

    ObjectMapper可以将java对象和json字符串相互转换

    ObjectMapper mapper = new ObjectMapper();
    Object readValue = mapper.readValue(json, Object.class);
    
    展开全文
  • <div><p>Currently the default Spring ObjectMapper is injected. <p>But in many applications it is already widely used and cannot be customized for graphql. <p>In my case a legacy app uses ObjectMapper ...
  • Customize ObjectMapper

    2021-01-07 19:49:42
    It would be nice if the buildObjectMapper can call some user logic to apply additional settings, best to create the actual ObjectMapper as it may require some arguments, then continue with current ...
  • ObjectMapper 使用

    2019-12-11 11:42:24
    public class TestObjectMapper { @Test public void objectToJSON() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); User user = new User(); user.set...
    public class TestObjectMapper {
    
        @Test
        public void objectToJSON() throws IOException {
    
            ObjectMapper objectMapper = new ObjectMapper();
            User user = new User();
            user.setId(1);
            user.setName("小明");
            user.setAge(18);
            user.setSex("男");
    
            String userJson = objectMapper.writeValueAsString(user);
            System.out.println(userJson);
    
    
            User user1 = objectMapper.readValue(userJson, User.class);
            System.out.println(user1.toString());
    
        }
    
        @Test
        public void listToJson() throws IOException {
            List<String> list = new ArrayList<>();
            list.add("username");
            list.add("password");
            list.add("accent");
            list.add("abc");
            ObjectMapper objectMapper = new ObjectMapper();
            String listJson = objectMapper.writeValueAsString(list);
            System.out.println(listJson);
    
            List list1 = objectMapper.readValue(listJson, List.class);
            System.out.println(list1);
        }
    
        @Test
        public void objectListToJson() throws IOException {
            List<User> userList = new ArrayList<>();
            User user0 = new User();
            user0.setId(1);
            user0.setName("小明");
            user0.setAge(18);
            user0.setSex("男");
            User user1 = new User();
            user1.setId(1);
            user1.setName("小明");
            user1.setAge(18);
            user1.setSex("男");
            User user2 = new User();
            user2.setId(1);
            user2.setName("小明");
            user2.setAge(18);
            user2.setSex("男");
    
            userList.add(user0);
            userList.add(user1);
            userList.add(user2);
    
            ObjectMapper objectMapper = new ObjectMapper();
            String userListJson = objectMapper.writeValueAsString(userList);
            System.out.println(userListJson);
    
            List<User> list = objectMapper.readValue(userListJson, List.class);
            System.out.println(list);
    
            User[] users = objectMapper.readValue(userListJson, User[].class);
            List<User> users1 = Arrays.asList(users);
            System.out.println(users1);
        }
    
    }
    
    展开全文
  • Jackson ObjectMapper

    2020-03-27 10:08:56
    Jackson ObjectMapper Example How Jackson ObjectMapper Matches JSON Fields to Java Fields Jackson Annotations Read Object From JSON String Read Object From JSON Reader Read Object From...
    Jackson Databind
    Jackson ObjectMapper Example
    How Jackson ObjectMapper Matches JSON Fields to Java Fields
    Jackson Annotations
    Read Object From JSON String
    Read Object From JSON Reader
    Read Object From JSON File
    Read Object From JSON via URL
    Read Object From JSON InputStream
    Read Object From JSON Byte Array
    Read Object Array From JSON Array String
    Read Object List From JSON Array String
    Read Map from JSON String
    Ignore Unknown JSON Fields
    Fail on Null JSON Values for Primitive Types
    Custom Deserializer
    Write JSON From Objects
    Custom Serializer
    Jackson Date Formats
        Date to long
        Date to String
    Jackson JSON Tree Model
        Jackson Tree Model Example
        The Jackson JsonNode Class
        Convert Object to JsonNode
        Convert JsonNode to Object
    Reading and Writing Other Data Formats With the Jackson ObjectMapper
    Reading and Writing CBOR With the Jackson ObjectMapper
    Reading and Writing MessagePack With the Jackson ObjectMapper
    Reading and Writing YAML With the Jackson ObjectMapper
    

    Jakob Jenkov
    Last update: 2019-09-24

    The Jackson ObjectMapper class (com.fasterxml.jackson.databind.ObjectMapper) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.

    The Jackson ObjectMapper can also create JSON from Java objects. Generating JSON from Java objects is also referred to as to serialize Java objects into JSON.

    The Jackson Object mapper can parse JSON into objects of classes developed by you, or into objects of the built-in JSON tree model explained later in this tutorial.

    By the way, the reason it is called ObjectMapper is because it maps JSON into Java Objects (deserialization), or Java Objects into JSON (serialization).
    Jackson Databind

    The ObjectMapper is located in the Jackson Databind project, so your application will need that project on its classpath to work. See the Jackson Installation tutorial for more information.
    Jackson ObjectMapper Example

    Here is a quick Java Jackson ObjectMapper example:

    ObjectMapper objectMapper = new ObjectMapper();

    String carJson =
    “{ “brand” : “Mercedes”, “doors” : 5 }”;

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

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

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

    The Car class was made by me. As you can see, the Car.class is parsed as the second parameter to the readValue() method. The first parameter of readValue() is the source of the JSON (string, stream or file). Here is how the Car class looks:

    public class Car {
    private String brand = null;
    private int doors = 0;

    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; }
    

    }

    How Jackson ObjectMapper Matches JSON Fields to Java Fields

    To read Java objects from JSON with Jackson properly, it is important to know how Jackson maps the fields of a JSON object to the fields of a Java object, so I will explain how Jackson does that.

    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.

    For instance, the JSON field named brand matches the Java getter and setter methods called getBrand() and setBrand(). The JSON field named engineNumber would match the getter and setter named getEngineNumber() and setEngineNumber().

    If you need to match JSON object fields to Java object fields in a different way, you need to either use a custom serializer and deserializer, or use some of the many Jackson Annotations.
    Jackson Annotations

    Jackson contains a set of Java annotations which you can use to modify how Jackson reads and writes JSON to and from Java objects. Jackson’s annotations are explained in my Jackson annotation tutorial.
    Read Object From JSON String

    Reading a Java object from a JSON string is pretty easy. You have actually already seen an example of how. The JSON string is passed as the first parameter to the ObjectMapper’s readValue() method. Here is another simplified example:

    ObjectMapper objectMapper = new ObjectMapper();

    String carJson =
    “{ “brand” : “Mercedes”, “doors” : 5 }”;

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

    Read Object From JSON Reader

    You can also read an object from JSON loaded via a Reader instance. Here is an example of how to do that:

    ObjectMapper objectMapper = new ObjectMapper();

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

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

    Read Object From JSON File

    Reading JSON from a file can of course be done via a FileReader (instead of a StringReader - see previous section), but also with a File object. Here is an example of reading JSON from a file:

    ObjectMapper objectMapper = new ObjectMapper();

    File file = new File(“data/car.json”);

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

    Read Object From JSON via URL

    You can read an object from JSON via a URL (java.net.URL) like this:

    ObjectMapper objectMapper = new ObjectMapper();

    URL url = new URL(“file:data/car.json”);

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

    This example uses a file URL, but you can use an HTTP URL too (similar to http://jenkov.com/some-data.json ).
    Read Object From JSON InputStream

    It is also possible to read an object from JSON via an InputStream with the Jackson ObjectMapper. Here is an example of reading JSON from an InputStream :

    ObjectMapper objectMapper = new ObjectMapper();

    InputStream input = new FileInputStream(“data/car.json”);

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

    Read Object From JSON Byte Array

    Jackson also supports reading objects from a JSON byte array. Here is an example of reading an object from a JSON byte array:

    ObjectMapper objectMapper = new ObjectMapper();

    String carJson =
    “{ “brand” : “Mercedes”, “doors” : 5 }”;

    byte[] bytes = carJson.getBytes(“UTF-8”);

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

    Read Object Array From JSON Array String

    The Jackson ObjectMapper can also read an array of objects from a JSON array string. Here is an example of reading an object array from a JSON array string:

    String jsonArray = “[{“brand”:“ford”}, {“brand”:“Fiat”}]”;

    ObjectMapper objectMapper = new ObjectMapper();

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

    Notice how the Car array class is passed as the second parameter to the readValue() method to tell the ObjectMapper that you want to read an array of Car instances.

    Reading arrays of objects also works with other JSON sources than a string. For instance, a file, URL, InputStream, Reader etc.
    Read Object List From JSON Array String

    The Jackson ObjectMapper can also read a Java List of objects from a JSON array string. Here is an example of reading a List of objects from a JSON array string:

    String jsonArray = “[{“brand”:“ford”}, {“brand”:“Fiat”}]”;

    ObjectMapper objectMapper = new ObjectMapper();

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

    Notice the TypeReference parameter passed to readValue(). This parameter tells Jackson to read a List of Car objects.
    Read Map from JSON String

    The Jackson ObjectMapper can also read a Java Map from a JSON string. This can be useful if you do not know ahead of time the exact JSON structure that you will be parsing. Usually you will be reading a JSON object into a Java Map. Each field in the JSON object will become a key, value pair in the Java Map.

    Here is an example of reading a Java Map from a JSON String with the Jackson ObjectMapper:

    String jsonObject = “{“brand”:“ford”, “doors”:5}”;

    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> jsonMap = objectMapper.readValue(jsonObject,
    new TypeReference<Map<String,Object>>(){});

    Ignore Unknown JSON Fields

    Sometimes you have more fields in the JSON than you do in the Java object you want to read from the JSON. By default Jackson throws an exception in that case, saying that it does not know field XYZ because it is not found in the Java object.

    However, sometimes it should be allowed to have more fields in the JSON than in the corresponding Java object. For instance, if you are parsing JSON from a REST service which contains much more data than you need. In that case, Jackson enables you to ignore these extra fields with a Jackson configuration. Here is how configuring the Jackson ObjectMapper to ignore unknown fields looks:

    objectMapper.configure(
    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Fail on Null JSON Values for Primitive Types

    It is possible to configure the Jackson ObjectMapper to fail if a JSON string contains a field with its value set to null, for a field which in the corresponding Java object is a primitive type (int, long, float, double etc.). To explain what I mean in more detail, look at this Car class:

    public class Car {
    private String brand = null;
    private int doors = 0;

    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; }
    

    }

    Notice how the doors field is an int which is a primitive type in Java (not an object).

    Now imagine you have a JSON string corresponding to a Car object which looks like this:

    { “brand”:“Toyota”, “doors”:null }

    Notice how the doors field contains the value null. A primitive type in Java cannot have the value null. Therefore the Jackson ObjectMapper by default ignores a null value for a primitive field. However, you can configure the Jackson ObjectMapper to fail instead. Here is how you configure the Jackson ObjectMapper to fail for null JSON values for primitive fields in Java classes:

    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);

    With FAIL_ON_NULL_FOR_PRIMITIVES configuration value set to true, you will get an exception when trying to parse a null JSON field into a primitive Java field. Here is a Java Jackson ObjectMapper example that will fail because a JSON field contains a null value for a primitive Java field:

    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);

    String carJson = “{ “brand”:“Toyota”, “doors”:null }”;

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

    Notice how the JSON string has the doors field set to null. The exception thrown from this code will look something like this:

    Exception in thread “main” com.fasterxml.jackson.databind.exc.MismatchedInputException:
    Cannot map null into type int
    (set DeserializationConfig.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES to ‘false’ to allow)
    at [Source: (String)
    “{ “brand”:“Toyota”, “doors”:null }”; line: 1, column: 29] (through reference chain: jackson.Car[“doors”])

    Custom Deserializer

    Sometimes you might want to read a JSON string into a Java object in a way that is different from how the Jackson ObjectMapper does this by default. You can add a custom deserializer to the ObjectMapper which can perform the deserialization as you want it done.

    Here is how you register and use a custom deserializer with the Jackson ObjectMapper:

    String json = “{ “brand” : “Ford”, “doors” : 6 }”;

    SimpleModule module =
    new SimpleModule(“CarDeserializer”, new Version(3, 1, 8, null, null, null));
    module.addDeserializer(Car.class, new CarDeserializer(Car.class));

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);

    Car car = mapper.readValue(json, Car.class);

    And here is how the CarDeserializer class looks:

    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.core.JsonToken;
    import com.fasterxml.jackson.databind.DeserializationContext;
    import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

    import java.io.IOException;

    public class CarDeserializer extends StdDeserializer {

    public CarDeserializer(Class<?> vc) {
        super(vc);
    }
    
    @Override
    public Car deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException {
        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());
                }
            }
        }
        return car;
    }
    

    }

    Write JSON From Objects

    The Jackson ObjectMapper can also be used to generate JSON from an object. You do so using the one of the methods:

    writeValue()
    writeValueAsString()
    writeValueAsBytes()
    

    Here is an example of generating JSON from a Car object, like the ones used in earlier examples:

    ObjectMapper objectMapper = new ObjectMapper();

    Car car = new Car();
    car.brand = “BMW”;
    car.doors = 4;

    objectMapper.writeValue(
    new FileOutputStream(“data/output-2.json”), car);

    This example first creates an ObjectMapper, then a Car instance, and finally calls the ObjectMapper’s writeValue() method which converts the Car object to JSON and writes it to the given FileOutputStream.

    The ObjectMapper’s writeValueAsString() and writeValueAsBytes() both generate JSON from an object, and return the generated JSON as a String or as a byte array. Here is an example showing how to call writeValueAsString():

    ObjectMapper objectMapper = new ObjectMapper();

    Car car = new Car();
    car.brand = “BMW”;
    car.doors = 4;

    String json = objectMapper.writeValueAsString(car);
    System.out.println(json);

    The JSON output from this example would be:

    {“brand”:“BMW”,“doors”:4}

    Custom Serializer

    Sometimes you want to serialize a Java object to JSON differently than what Jackson does by default. For instance, you might want to use different field names in the JSON than in the Java object, or you might want to leave out certain fields altogether.

    Jackson enables you to set a custom serializer on the ObjectMapper. This serializer is registered for a certain class, and will then be called whenever the ObjectMapper is asked to serialize a Car object. Here is an example that shows how to register a custom serializer for the Car class:

    CarSerializer carSerializer = new CarSerializer(Car.class);
    ObjectMapper objectMapper = new ObjectMapper();

    SimpleModule module =
    new SimpleModule(“CarSerializer”, new Version(2, 1, 3, null, null, null));
    module.addSerializer(Car.class, carSerializer);

    objectMapper.registerModule(module);

    Car car = new Car();
    car.setBrand(“Mercedes”);
    car.setDoors(5);

    String carJson = objectMapper.writeValueAsString(car);

    The string produced by this Jackson custom serializer example looks like this:

    {“producer”:“Mercedes”,“doorCount”:5}

    The CarSerializer class looks like this:

    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.ser.std.StdSerializer;

    import java.io.IOException;

    public class CarSerializer extends StdSerializer {

    protected CarSerializer(Class<Car> t) {
        super(t);
    }
    
    public void serialize(Car car, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider)
            throws IOException {
    
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("producer", car.getBrand());
        jsonGenerator.writeNumberField("doorCount", car.getDoors());
        jsonGenerator.writeEndObject();
    }
    

    }

    Notice that the second parameter passed to the serialize() method is a Jackson JsonGenerator instance. You can use this instance to serialize the object - in this case a Car object.
    Jackson Date Formats

    By default Jackson will serialize a java.util.Date object to its long value, which is the number of milliseconds since January 1st 1970. However, Jackson also supports formatting dates as strings. In this section we will take a closer look at the Jackson date formats.
    Date to long

    First I will show you the default Jackson date format that serializes a Date to the number of milliseconds since January 1st 1970 (its long representation). Here is an example Java class that contains a Date field:

    public class Transaction {
    private String type = null;
    private Date date = null;

    public Transaction() {
    }
    
    public Transaction(String type, Date date) {
        this.type = type;
        this.date = date;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String type) {
        this.type = type;
    }
    
    public Date getDate() {
        return date;
    }
    
    public void setDate(Date date) {
        this.date = date;
    }
    

    }

    Serializing a Transaction object with the Jackson ObjectMapper would be done just as you would serialize any other Java object. Here is how the code looks:

    Transaction transaction = new Transaction(“transfer”, new Date());

    ObjectMapper objectMapper = new ObjectMapper();
    String output = objectMapper.writeValueAsString(transaction);

    System.out.println(output);

    The output printed from this example would be similar to:

    {“type”:“transfer”,“date”:1516442298301}

    Notice the format of the date field: It is a long number, just as explained above.
    Date to String

    The long serialization format of a Date is not very readable for human beings. Therefore Jackson supports a textual date format too. You specify the exact Jackson date format to use by setting a SimpleDateFormat on the ObjectMapper. Here is an example of setting a SimpleDateFormat on a Jackson ObjectMapper:

    SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd”);
    objectMapper2.setDateFormat(dateFormat);

    String output2 = objectMapper2.writeValueAsString(transaction);
    System.out.println(output2);

    The output printed from this example would look similar to this:

    {“type”:“transfer”,“date”:“2018-01-20”}

    Notice how the date field is now formatted as a String.
    Jackson JSON Tree Model

    Jackson has a built-in tree model which can be used to represent a JSON object. Jackson’s tree model is useful if you don’t know how the JSON you will receive looks, or if you for some reason cannot (or just don’t want to) create a class to represent it. The Jackson Tree Model is also useful if you need to manipulate the JSON before using or forwarding it. All of these situations can easily occur in a Data Streaming scenario.

    The Jackson tree model is represented by the JsonNode class. You use the Jackson ObjectMapper to parse JSON into a JsonNode tree model, just like you would have done with your own class.

    The following sections will show how to read and write JsonNode instances with the Jackson ObjectMapper. The Jackson JsonNode class itself is covered in more detail in its own tutorial about the Jackson JsonNode.
    Jackson Tree Model Example

    Here is a simple Jackson tree model example:

    String carJson =
    “{ “brand” : “Mercedes”, “doors” : 5 }”;

    ObjectMapper objectMapper = new ObjectMapper();

    try {

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

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

    As you can see, the JSON string is parsed into a JsonNode object instead of a Car object, simply by passing the JsonNode.class as second parameter to the readValue() method instead of the Car.class used in the example earlier in this tutorial.

    The ObjectMapper class also has a special readTree() method which always returns a JsonNode. Here is an example of parsing JSON into a JsonNode with the ObjectMapper readTree() method:

    String carJson =
    “{ “brand” : “Mercedes”, “doors” : 5 }”;

    ObjectMapper objectMapper = new ObjectMapper();

    try {

    JsonNode jsonNode = objectMapper.readTree(carJson);
    

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

    The Jackson JsonNode Class

    The JsonNode class lets you navigate the JSON as a Java object in a quite flexible and dynamic way. As mentioned earlier, the JsonNode class is covered in more detail in its own tutorial, but I will just show you the basics of how to use it here.

    Once you have parsed your JSON into a JsonNode (or a tree of JsonNode instances) you can navigate the JsonNode tree model. Here is a JsonNode example that shows how to access JSON fields, arrays and nested objects:

    String carJson =
    “{ “brand” : “Mercedes”, “doors” : 5,” +
    " “owners” : [“John”, “Jack”, “Jill”]," +
    " “nestedObject” : { “field” : “value” } }";

    ObjectMapper objectMapper = new ObjectMapper();

    try {

    JsonNode jsonNode = objectMapper.readValue(carJson, JsonNode.class);
    
    JsonNode brandNode = jsonNode.get("brand");
    String brand = brandNode.asText();
    System.out.println("brand = " + brand);
    
    JsonNode doorsNode = jsonNode.get("doors");
    int doors = doorsNode.asInt();
    System.out.println("doors = " + doors);
    
    JsonNode array = jsonNode.get("owners");
    JsonNode jsonNode = array.get(0);
    String john = jsonNode.asText();
    System.out.println("john  = " + john);
    
    JsonNode child = jsonNode.get("nestedObject");
    JsonNode childField = child.get("field");
    String field = childField.asText();
    System.out.println("field = " + field);
    

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

    Notice that the JSON string now contains an array field called owners and a nested object field called nestedObject.

    Regardless of whether you are accessing a field, array or nested object you use the get() method of the JsonNode class. By providing a string as parameter to the get() method you can access a field of a JsonNode. If the JsonNode represents an array, you need to pass an index to the get() method instead. The index specifies what element in the array you want to get.
    Convert Object to JsonNode

    It is possible to use the Jackson ObjectMapper to convert a Java object to a JsonNode with the JsonNode being a JSON representation of the Java object converted. You convert a Java object to a JsonNode via the Jackson ObjectMapper valueToTree() method. Here is an example of converting a Java object to a JsonNode using the ObjectMapper valueToTree() method:

    ObjectMapper objectMapper = new ObjectMapper();

    Car car = new Car();
    car.brand = “Cadillac”;
    car.doors = 4;

    JsonNode carJsonNode = objectMapper.valueToTree(car);

    Convert JsonNode to Object

    You can convert a JsonNode to a Java object, using the Jackson ObjectMapper treeToValue() method. This is similar to parsing a JSON string (or other source) into a Java object with the Jackson ObjectMapper. The only difference is, that the JSON source is a JsonNode. Here is an example of converting a JsonNode to a Java object using the Jackson ObjectMapper treeToValue() method:

    ObjectMapper objectMapper = new ObjectMapper();

    String carJson = “{ “brand” : “Mercedes”, “doors” : 5 }”;

    JsonNode carJsonNode = objectMapper.readTree(carJson);

    Car car = objectMapper.treeToValue(carJsonNode);

    The example above is a bit “artificial” in that we first convert a JSON string to a JsonNode and then convert the JsonNode to a Car object. Obviously, if we have a reference to a raw JSON string you might as well convert it directly to a Car object, without converting it to a JsonNode first. However, the example above is constructed to show how to convert a JsonNode to a Java object. That is why.
    Reading and Writing Other Data Formats With the Jackson ObjectMapper

    It is possible to read and write other data formats than JSON with the Jackson ObjectMapper. The Jackson ObjectMapper can read and write these data formats too (and possibly more):

    CBOR
    MessagePack
    YAML
    

    Some of these data formats are more compact than JSON, and therefore take up less space when stored, and are faster to read and write than JSON is. In the following sections I will show you how to read and write some of these data formats with the Jackson ObjectMapper.
    Reading and Writing CBOR With the Jackson ObjectMapper

    CBOR is a binary data format which is compatible with JSON but which is more compact than JSON, and thus faster to read and write. The Jackson ObjectMapper can read and write CBOR in the same way you read and write JSON. In order to read and write CBOR with Jackson, you need to add an extra Maven dependency to your project. Adding the Jackson CBOR Maven dependency is covered in the Jackson Installation Tutorial. Here is an example of writing an object to CBOR with the Jackson ObjectMapper:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.cbor.CBORFactory;

    public class CborJacksonExample {
    public static void main(String[] args) {
    ObjectMapper objectMapper = new ObjectMapper(new CBORFactory());

        Employee employee = new Employee("John Doe", "john@doe.com");
    
        try {
            byte[] cborBytes = objectMapper.writeValueAsBytes(employee);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    

    }

    The cborBytes byte array contains the Employee object serialized to the CBOR data format.

    Here is an example of reading the CBOR bytes back into an Employee object again:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.cbor.CBORFactory;

    import java.io.IOException;

    public class CborJacksonExample {
    public static void main(String[] args) {
    ObjectMapper objectMapper = new ObjectMapper(new CBORFactory());

        Employee employee = new Employee("John Doe", "john@doe.com");
    
        byte[] cborBytes = null;
        try {
            cborBytes = objectMapper.writeValueAsBytes(employee);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // normally, rethrow exception here - or don't catch it at all.
        }
    
        try {
            Employee employee2 = objectMapper.readValue(cborBytes, Employee.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    }

    After running this code, the employee2 will point to a different Employee object but which is equal to the object the employee is pointing to, because that object was serialized to CBOR and deserialized back to employee2 again.
    Reading and Writing MessagePack With the Jackson ObjectMapper

    YAML is a textual data format which is compatible with JSON but more compact, and thus faster to read and write. The Jackson ObjectMapper can read and write MessagePack in the same way you read and write JSON. In order to read and write MessagePack with Jackson, you need to add an extra Maven dependency to your project. Adding the Jackson MessagePack Maven dependency is covered in the Jackson Installation Tutorial. Here is an example of writing an object to MessagePack with the Jackson ObjectMapper:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.msgpack.jackson.dataformat.MessagePackFactory;

    import java.io.IOException;

    public class MessagePackJacksonExample {
    public static void main(String[] args) {
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());

        Employee employee = new Employee("John Doe", "john@doe.com");
    
        byte[] messagePackBytes = null;
        try {
            messagePackBytes = objectMapper.writeValueAsBytes(employee);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // normally, rethrow exception here - or don't catch it at all.
        }
    }
    

    }

    The messagePackBytes byte array contains the Employee object serialized to the MessagePack data format.

    Here is an example of reading the MessagePack bytes back into an Employee object again:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.msgpack.jackson.dataformat.MessagePackFactory;

    import java.io.IOException;

    public class MessagePackJacksonExample {
    public static void main(String[] args) {
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());

        Employee employee = new Employee("John Doe", "john@doe.com");
    
        byte[] messagePackBytes = null;
        try {
            messagePackBytes = objectMapper.writeValueAsBytes(employee);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // normally, rethrow exception here - or don't catch it at all.
        }
    
        try {
            Employee employee2 = objectMapper.readValue(messagePackBytes, Employee.class);
            System.out.println("messagePackBytes = " + messagePackBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    

    }

    After running this code, the employee2 will point to a different Employee object but which is equal to the object the employee is pointing to, because that object was serialized to MessagePack and deserialized back to employee2 again.
    Reading and Writing YAML With the Jackson ObjectMapper

    YAML is a textual data format which is similar to JSON but uses a different syntax. The Jackson ObjectMapper can read and write YAML in the same way you read and write JSON. In order to read and write YAML with Jackson, you need to add an extra Maven dependency to your project. Adding the Jackson YAML Maven dependency is covered in the Jackson Installation Tutorial. Here is an example of writing an object to YAML with the Jackson ObjectMapper:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

    import java.io.IOException;

    public class YamlJacksonExample {

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    
        Employee employee = new Employee("John Doe", "john@doe.com");
    
        String yamlString = null;
        try {
            yamlString = objectMapper.writeValueAsString(employee);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // normally, rethrow exception here - or don't catch it at all.
        }
    
    }
    

    }

    The yamlString variable contains the Employee object serialized to the YAML data format after executing this code.

    Here is an example of reading the YAML text into an Employee object again:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

    import java.io.IOException;

    public class YamlJacksonExample {

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    
        Employee employee = new Employee("John Doe", "john@doe.com");
    
        String yamlString = null;
        try {
            yamlString = objectMapper.writeValueAsString(employee);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // normally, rethrow exception here - or don't catch it at all.
        }
    
        try {
            Employee employee2 = objectMapper.readValue(yamlString, Employee.class);
    
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    

    }

    After running this code, the employee2 will point to a different Employee object but which is equal to the object the employee is pointing to, because that object was serialized to YAML and deserialized back to employee2 again.
    Next: Jackson JsonNode
    Tweet

    Jakob Jenkov

    展开全文
  • ObjectMapper

    2019-01-22 10:32:17
    web程序,前后端之间数据交流,一般通过json数据通信,这时候会涉及到json数据格式的统一问题,这个时候一般使用ObjectMapper进行重写来统一数据格式。 ObjectMapper 类是Jackson的主要类,主要实现java类和json...

    背景:

    web程序,前后端之间数据交流,一般通过json数据通信,这时候会涉及到json数据格式的统一问题,这个时候一般使用ObjectMapper进行重写来统一数据格式。

    ObjectMapper 类是Jackson的主要类,主要实现java类和json对象之间的转换。

    // 使用ObjectMapper来转化对象为Json
    final static ObjectMapper MAPPER = new ObjectMapper();
    static {
    		
    //这个特性决定parser是否将允许使用非双引号属性名字		
    MAPPER.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES,false);
    	}
    

    我们看一下 jackson的配置属性。

    /**
         * Enumeration that defines all togglable features for parsers.
         */
        public enum Feature {
     
            // // // Low-level I/O handling features:
     
            /**
             * 这个特性,决定了解析器是否将自动关闭那些不属于parser自己的输入源。 如果禁止,则调用应用不得不分别去关闭那些被用来创建parser的基础输入流InputStream和reader;
             * 如果允许,parser只要自己需要获取closed方法(当遇到输入流结束,或者parser自己调用 JsonParder#close方法),就会处理流关闭。
             *
             * 注意:这个属性默认是true,即允许自动关闭流
             *
             */
            AUTO_CLOSE_SOURCE(true),
     
            // // // Support for non-standard data format constructs
     
            /**
             * 该特性决定parser将是否允许解析使用Java/C++ 样式的注释(包括'/'+'*' 和'//' 变量)。 由于JSON标准说明书上面没有提到注释是否是合法的组成,所以这是一个非标准的特性;
             * 尽管如此,这个特性还是被广泛地使用。
             *
             * 注意:该属性默认是false,因此必须显式允许,即通过JsonParser.Feature.ALLOW_COMMENTS 配置为true。
             *
             */
            ALLOW_COMMENTS(false),
     
            /**
             * 这个特性决定parser是否将允许使用非双引号属性名字, (这种形式在Javascript中被允许,但是JSON标准说明书中没有)。
             *
             * 注意:由于JSON标准上需要为属性名称使用双引号,所以这也是一个非标准特性,默认是false的。
             * 同样,需要设置JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES为true,打开该特性。
             *
             */
            ALLOW_UNQUOTED_FIELD_NAMES(false),
     
            /**
             * 该特性决定parser是否允许单引号来包住属性名称和字符串值。
             *
             * 注意:默认下,该属性也是关闭的。需要设置JsonParser.Feature.ALLOW_SINGLE_QUOTES为true
             *
             */
            ALLOW_SINGLE_QUOTES(false),
     
            /**
             * 该特性决定parser是否允许JSON字符串包含非引号控制字符(值小于32的ASCII字符,包含制表符和换行符)。 如果该属性关闭,则如果遇到这些字符,则会抛出异常。
             * JSON标准说明书要求所有控制符必须使用引号,因此这是一个非标准的特性。
             *
             * 注意:默认时候,该属性关闭的。需要设置:JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS为true。
             *
             */
            ALLOW_UNQUOTED_CONTROL_CHARS(false),
     
            /**
             * 该特性可以允许接受所有引号引起来的字符,使用‘反斜杠\’机制:如果不允许,只有JSON标准说明书中 列出来的字符可以被避开约束。
             *
             * 由于JSON标准说明中要求为所有控制字符使用引号,这是一个非标准的特性,所以默认是关闭的。
             *
             * 注意:一般在设置ALLOW_SINGLE_QUOTES属性时,也设置了ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER属性,
             * 所以,有时候,你会看到不设置ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER为true,但是依然可以正常运行。
             *
             * @since 1.6
             */
            ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER(false),
     
            /**
             * 该特性决定parser是否允许JSON整数以多个0开始(比如,如果000001赋值给json某变量,
             * 如果不设置该属性,则解析成int会抛异常报错:org.codehaus.jackson.JsonParseException: Invalid numeric value: Leading zeroes not
             * allowed)
             *
             * 注意:该属性默认是关闭的,如果需要打开,则设置JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS为true。
             *
             * @since 1.8
             */
            ALLOW_NUMERIC_LEADING_ZEROS(false),
     
            /**
             * 该特性允许parser可以识别"Not-a-Number" (NaN)标识集合作为一个合法的浮点数。 例如: allows (tokens are quoted contents, not including
             * quotes):
             * <ul>
             * <li>"INF" (for positive infinity), as well as alias of "Infinity"
             * <li>"-INF" (for negative infinity), alias "-Infinity"
             * <li>"NaN" (for other not-a-numbers, like result of division by zero)
             * </ul>
             */
     
            ALLOW_NON_NUMERIC_NUMBERS(false),
     
            // // // Controlling canonicalization (interning etc)
     
            /**
             * 该特性决定JSON对象属性名称是否可以被String#intern 规范化表示。
             *
             * 如果允许,则JSON所有的属性名将会 intern() ;如果不设置,则不会规范化,
             *
             * 默认下,该属性是开放的。此外,必须设置CANONICALIZE_FIELD_NAMES为true
             *
             * 关于intern方法作用:当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串 (该对象由 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String
             * 对象添加到池中, 并且返回此 String 对象的引用。
             *
             * @since 1.3
             */
            INTERN_FIELD_NAMES(true),
     
            /**
             * 该特性决定JSON对象的属性名称是否被规范化。
             *
             * @since 1.5
             */
            CANONICALIZE_FIELD_NAMES(true),
     
            ;
     
            final boolean _defaultState;
     
            /**
             * Method that calculates bit set (flags) of all features that are enabled by default.
             */
            public static int collectDefaults() {
                int flags = 0;
                for (Feature f : values()) {
                    if (f.enabledByDefault()) {
                        flags |= f.getMask();
                    }
                }
                return flags;
            }
     
            private Feature(boolean defaultState) {
                _defaultState = defaultState;
            }
     
            public boolean enabledByDefault() {
                return _defaultState;
            }
     
            public boolean enabledIn(int flags) {
                return (flags & getMask()) != 0;
            }
     
            public int getMask() {
                return (1 << ordinal());
            }
        };
    
    
    展开全文
  • ObjectMapper2

    2019-08-06 05:20:21
    ObjectMapper mapper = new ObjectMapper(); try { user = mapper.readValue(new StringReader(json), User.class); } catch (JsonParseException e) { ...
  • 3ObjectMapper

    2019-06-13 17:50:11
    https://www.cnblogs.com/xuwenjin/p/8976696.html https://blog.csdn.net/han1196639488/article/details/79358743 ObjectMapper mapper = new ObjectMapper(); JsonNode jsonObj = null; ...
  • <div><p>It looks like that <code>ObjectMapper.valueToTree</code> ignores enabled features, and in general outputs something very different than methods which actually produce JSON, such as <code>...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,247
精华内容 2,098
关键字:

objectmapper