Jaskson ObjectMapper

原文:https://www.studytonight.com/java-examples/jackson-objectmapper

JasksonObjectMapper类用于将对象映射到 JSON 或将 JSON 映射到对象。这是一个简单易用的类,为我们提供了许多不同的选项来解析 JSON。

JSON 是一种广泛使用的文件格式,用于存储和传输类的属性值对。

在本教程中,我们将了解更多关于此类的信息。

在 Java 中使用对象映射器读取

我们可以使用ObjectMapper类从 JSON 文件、JSON 字符串或网址,甚至 JSON 字符串数组中读取对象。

我们将在本教程中使用下面定义的类。在继续学习本教程之前,请确保将必要的依赖项或 jar 文件添加到类路径中。

class DemoClass
{
    private String field1;
    private Double field2;

    //Constructors
    DemoClass()
    {}    
    DemoClass(String field1, Double field2)
    {
        this.field1 = field1;
        this.field2 = field2;
    }    
    //getters and setters
    public String getField1() {
        return field1;
    }
    public void setField1(String field1) {
        this.field1 = field1;
    }
    public Double getField2() {
        return field2;
    }
    public void setField2(Double field2) {
        this.field2 = field2;
    }
}

从 JSON 文件中读取对象

我们可以使用这个类的 readValue() 方法,将 JSON 文件中的数据读入一个对象。我们的 JSON 文件只包含单个对象的属性值对。

import java.io.File;

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            //File to read from
            String filePath = "C:\\Users\\Lenovo\\Desktop\\jsonDemo.json";
            File file = new File(filePath);

            ObjectMapper objMapper = new ObjectMapper();
            DemoClass obj = new DemoClass();
            obj = objMapper.readValue(file, DemoClass.class);

            System.out.print(obj.getField1() + " " + obj.getField2());
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

样品 1 20.21

从 JSON 字符串中读取对象

我们可以将 JSON 文件的内容复制到一个 Java 字符串中,并从这个字符串创建一个对象。我们将再次使用ObjectMapper类的readValue()方法。我们还需要将Class类型传递给这个方法。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21}";
            ObjectMapper objMapper = new ObjectMapper();

            DemoClass obj = new DemoClass();
            obj = objMapper.readValue(jsonString, DemoClass.class);

            System.out.print(obj.getField1() + " " + obj.getField2());
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

样品 1 20.21

从 JSON 网址读取对象

从网址中读取对象也非常简单。我们需要将 URL 对象和Class类型传递给readValue()方法。

import java.net.URL;
public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            ObjectMapper objMapper = new ObjectMapper();

            URL jsonFileUrl = new URL("file:C:\\Users\\Lenovo\\Desktop\\jsonDemo.json");
            DemoClass obj = new DemoClass();
            obj = objMapper.readValue(jsonFileUrl, DemoClass.class);

            System.out.print(obj.getField1() + " " + obj.getField2());
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

样品 1 20.21

从 JSON 字符串数组读取到对象数组

假设一个字符串包含多个 JSON 格式的对象数据(作为数组)。我们可以使用ObjectMapper类将所有这些数据读入Class类型的数组。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            //String with two DemoClass Objects
            String jsonString = "[{\"field1\":\"Sample-1\",\"field2\":20.21}, {\"field1\":\"Sample-2\",\"field2\":22.55}]";
            ObjectMapper objMapper = new ObjectMapper();
            //Reading into an object array
            DemoClass[] objectArr = objMapper.readValue(jsonString, DemoClass[].class);
            //Printing the objects
            for(DemoClass obj : objectArr)
                System.out.println(obj.getField1() + " " + obj.getField2());
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

样品 1 20.21 样品 2 22.55

从 JSON 字符串数组读取对象列表

如果不想将数据读入固定大小的对象数组,我们可以将对象读入列表。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            //String with two DemoClass Objects
            String jsonString = "[{\"field1\":\"Sample-1\",\"field2\":20.21}, {\"field1\":\"Sample-2\",\"field2\":22.55}]";
            ObjectMapper objMapper = new ObjectMapper();

            //Reading into an object List
            List<DemoClass> objectList = objMapper.readValue(jsonString, new TypeReference<List<DemoClass>>(){});

            //Printing the objects
            for(DemoClass obj : objectList)
                System.out.println(obj.getField1() + " " + obj.getField2());
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

样品 1 20.21 样品 2 22.55

从 JSON 字符串数组读取对象映射

我们还可以将 JSON 字符串中的数据读入到 Map 中。类的每个属性将成为一个键,属性值将成为值。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21}";

            ObjectMapper objMapper = new ObjectMapper();
            //Reading into an object Map
            Map<String, Object> objectMap = objMapper.readValue(jsonString, HashMap.class);

            for(Map.Entry<String, Object> e : objectMap.entrySet())
                System.out.println(e.getKey() + " " + e.getValue());
        }

        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

字段 1 样本-1 字段 2 20.21

将 JSON 读取到 JsonNode 对象

JsonNode类为我们提供了一种更灵活的解析 JSON 的方式。我们可以使用ObjectMapper类的 readTree() 方法将 JSON 读入一个 JsonNode 对象。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            //String with two DemoClass Objects
            String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21}";
            ObjectMapper objMapper = new ObjectMapper();

            JsonNode node = objMapper.readTree(jsonString);
            String field1 = node.get("field1").asText();
            String field2 = node.get("field2").asText();

            System.out.print(field1 + " " + field2);            
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

样品 1 20.21

从对象编写 JSON

我们可以使用ObjectMapper类将对象写入 JSON 文件。这个类的**writeValue()**方法用来序列化一个对象,并将它写入一个 JSON 文件。

import java.io.File;
public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        DemoClass obj = new DemoClass("Sample-1", 20.21);//object to write        
        try
        {
            //File to write object in
            String filePath = "C:\\Users\\Lenovo\\Desktop\\jsonDemo.json";
            File file = new File(filePath);

            ObjectMapper objMapper = new ObjectMapper();
            objMapper.writeValue(file, obj);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

JSON 文件的内容如下所示。

{“field 1”:“Sample-1”、“field 2”:20.21 }

将对象序列化为 JSON

我们也可以使用**writeValueAsString()**方法将一个对象序列化为 JSON 字符串。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        DemoClass obj = new DemoClass("Sample-1", 20.21);//object to write        
        try
        {
            ObjectMapper objMapper = new ObjectMapper();
            String jsonString = objMapper.writeValueAsString(obj);//Generating JSON as a String
            System.out.print(jsonString);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

{“field 1”:“Sample-1”、“field 2”:20.21 }

同样的,**writeValueAsBytes()**会返回一个对象对应的字节数组。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        DemoClass obj = new DemoClass("Sample-1", 20.21);//object to write        
        try
        {
            ObjectMapper objMapper = new ObjectMapper();
            byte[] jsonByteArr = objMapper.writeValueAsBytes(obj);
            String strFromByteArr = new String(jsonByteArr);
            System.out.print(strFromByteArr);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

{“field 1”:“Sample-1”、“field 2”:20.21 }

配置对象映射器

我们可以对ObjectMapper进行配置,这样它就可以处理意外的输入。例如,读取具有一些未知属性的 JSON 字符串将导致**UnrecognizedPropertyException**。下面的代码演示了这一点。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            //String with an unknown field3 property
            String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21,\"field3\":\"Unknown\"}";
            ObjectMapper objMapper = new ObjectMapper();

            DemoClass obj = new DemoClass();
            obj = objMapper.readValue(jsonString, DemoClass.class);    
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

我们可以配置我们的ObjectMapper忽略任何新的属性。这是通过使用配置()方法完成的。

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            //String with an unknown field3 property
            String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21,\"field3\":\"Unknown\"}";
            ObjectMapper objMapper = new ObjectMapper();
            objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            DemoClass obj = new DemoClass();
            obj = objMapper.readValue(jsonString, DemoClass.class);    
            System.out.print(obj.getField1() + " " + obj.getField2());
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

样品 1 20.21

我们还可以将ObjectMapper配置为使用原始类型的空值。

ObjectMapper objMapper = new ObjectMapper();

objMapper .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);

使用日期

默认情况下,对象映射器将把一个java.util.date映射到一个长值。这个长值是自 1970 年 1 月 1 日以来经过的毫秒数。这不是一个非常方便的格式。

让我们向我们的 DemoClass 添加一个日期字段,并将一个对象序列化到 JSON。

class DemoClass
{
    private String field1;
    private Double field2;
    private Date dateField;

    //Constructors
    DemoClass()
    {}    
    DemoClass(String field1, Double field2, Date d)
    {
        this.field1 = field1;
        this.field2 = field2;
        this.dateField = d;
    }    
    //getters and setters
}
public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            DemoClass obj = new DemoClass("Sample-1", 20.21, new Date());
            ObjectMapper objMapper = new ObjectMapper();

            String jsonString = objMapper.writeValueAsString(obj);
            System.out.print(jsonString);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

{“field 1”:“Sample-1”,“field 2”:20.21,“dateField”:1627623983148 }

但是,我们可以使用SimpleDateFormat来定义日期格式,以序列化java.util.date

public class ObjectMapperDemo
{
    public static void main(String[] args)
    {
        try
        {
            ObjectMapper objMapper = new ObjectMapper();
            //Creating and setting a date format
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yy");
            objMapper.setDateFormat(dateFormat);

            DemoClass obj = new DemoClass("Sample-1", 20.21, new Date());
            String jsonString = objMapper.writeValueAsString(obj);
            System.out.print(jsonString);
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

{“field 1”:“Sample-1”,“field 2”:20.21,“dateField”:“30-07-21”}

摘要

Jaskson 库的ObjectMapper类提供了大量使用 JSON 格式的工具。在本教程中,我们学习了这门课的一些基础知识。我们学习了如何将 Java 对象序列化为 JSON,以及如何将 JSON 反序列化为 Java 对象。