Jackson使用示例——Bean、XML、Json互转

前言


目前常见的json解析工具有jackson、fastjson、gson;

  • jackson是spring mvc内置的json转换工具;
  • fastjson是阿里的开源JSON解析库,由于fastjson经常会出现漏洞,所以很多人都不再用了;

Jaskson相关注解


注解 说明
@JsonProperties 把属性的名称序列化时转换为另外一个名称 ;@JsonProperty(“DepName”)
@JsonFormat 把属性的格式序列化时转换成指定的格式;@JsonFormat(pattern = “yyyy-MM-dd”)
@JsonPropertyOrder 指定属性在序列化时 json 中的顺序;@JsonPropertyOrder({ “age”, “name” })
@JsonIgnore 排除指定属性不被json序列化
@JacksonXmlProperty 指定XML命名空间的名称;@JacksonXmlProperty(localName = “DepName”)
@JacksonXmlRootElement 指定XML根元素命名空间的名称;@JacksonXmlRootElement(localName = “RootName”)
@JacksonXmlElementWrapper 可用于指定List等集合类,外围标签名;@JacksonXmlElementWrapper(localName = “EmpMessage”)

1、对象和json互转


引入jackson相关依赖:

<dependency>
	<groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-annotationsartifactId>
dependency>

<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-coreartifactId>
dependency>

<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
dependency>

<dependency>
    <groupId>com.fasterxml.jackson.datatypegroupId>
    <artifactId>jackson-datatype-jsr310artifactId>
dependency>

<dependency>
    <groupId>com.fasterxml.jackson.dataformatgroupId>
    <artifactId>jackson-dataformat-xmlartifactId>
dependency>

Employees实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employees {
     
    private String name;
    private Integer age;
    private String sex;
}
测试代码:
/**
 * @author 秋一叶
 * @create 2020-12-31 22:00
 * json字符串和对象、集合、map互转
 *
 */
public class Demo2 {
     
    public static void main(String[] args) {
     
   		ObjectMapper objectMapper = new ObjectMapper();
        Employees employees1 = new Employees("秋一叶",18,"男");
        Employees employees2 = new Employees("小王",20,"男");
        
        try {
     
            //对象转json字符串
            String jsonString = objectMapper.writeValueAsString(employees1);
            //json字符串转为对象
            Employees emp1 = objectMapper.readValue(jsonString, Employees.class);
            System.out.println("json字符串:" + jsonString);
            System.out.println("对象1:" + emp1);

            System.out.println("====================================================");

            //对象转为json字符串写入文件
            objectMapper.writeValue(new File("emp.json"), employees1);
            //从文件中读取json字符串转为对象
            Employees emp2 = objectMapper.readValue(new File("emp.json"), Employees.class);
            System.out.println("对象2:" + emp2);

            System.out.println("====================================================");

            //对象写为字节流
            byte[] bytes = objectMapper.writeValueAsBytes(employees1);
            //字节流转为对象
            Employees emp3 = objectMapper.readValue(bytes, Employees.class);
            System.out.println("对象3:" + emp3);

            System.out.println();
            System.out.println("*****************************************************");
            System.out.println();


            //Map和json互转
            Map<String, Object> map = Maps.newHashMap();
            map.put("001", employees1);
            map.put("002", "元旦");
            String mapToString = objectMapper.writeValueAsString(map);
            Map<String, Object> stringToMap = objectMapper.readValue(mapToString, new TypeReference<Map<String, Object>>() {
     
            });
            System.out.println("json字符串:" + mapToString);
            System.out.println("map:" + stringToMap);

            System.out.println("====================================================");

            //List和json互转
            List<Employees> empList = Lists.newArrayList(employees1, employees2);
            String jsonList = objectMapper.writeValueAsString(empList);
            List<Employees> stringToList = objectMapper.readValue(jsonList, new TypeReference<List<Employees>>() {
     
            });
            System.out.println("json字符串:" + jsonList);
            System.out.println("map:" + stringToList);

        } catch (IOException e) {
     
            e.printStackTrace();
        }
    }
}
打印结果:
json字符串:{"name":"秋一叶","age":18,"sex":"男"}
对象1:Employees(name=秋一叶, age=18, sex=男)
====================================================
对象2:Employees(name=秋一叶, age=18, sex=男)
====================================================
对象3:Employees(name=秋一叶, age=18, sex=男)

*****************************************************

json字符串:{"001":{"name":"秋一叶","age":18,"sex":"男"},"002":"元旦"}
map:{001={name=秋一叶, age=18, sex=男}, 002=元旦}
====================================================
json字符串:[{"name":"秋一叶","age":18,"sex":"男"},{"name":"小王","age":20,"sex":"男"}]
map:[Employees(name=秋一叶, age=18, sex=男), Employees(name=小王, age=20, sex=男)]


2、XML和对象互转

Department实体:
@Data
@JacksonXmlRootElement(localName = "RootName")
public class Department {
     
    @JacksonXmlProperty(localName = "DepName")
    private String depName;
    
    @JacksonXmlElementWrapper(localName = "EmpMessage")
    @JacksonXmlProperty(localName = "EmpName")
    List<Employees> employees; 
}
测试代码:
public class Demo1 {
     
    public static void main(String[] args) {
     
        XmlMapper xmlMapper = new XmlMapper();
        //字段为null,自动忽略,不再序列化
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        Department department = new Department();
        Employees employees1 = new Employees("秋一叶",18,"男");
        Employees employees2 = new Employees("小王",20,"男");
        department.setDepName("产品研发部门");
        department.setEmployees(Lists.newArrayList(employees1, employees2));

        try {
     
            //对象转xml
            String xml = xmlMapper.writeValueAsString(department);
            //xml转对象
            Department dep = xmlMapper.readValue(xml, Department.class);

            System.out.println("返回的xml:" + xml);
            System.out.println("返回的实体:" + dep);
        } catch (JsonProcessingException e) {
     
            e.printStackTrace();
        }
    }
}
打印结果:
返回的xml:<RootName><DepName>产品研发部门DepName><EmpMessage><EmpName><name>秋一叶name><age>18age><sex>sex>EmpName><EmpName><name>小王name><age>20age><sex>sex>EmpName>EmpMessage>RootName>
返回的实体:Department(depName=产品研发部门, employees=[Employees(name=秋一叶, age=18, sex=男), Employees(name=小王, age=20, sex=男)])

Jackson使用示例——Bean、XML、Json互转_第1张图片

你可能感兴趣的:(JAVA,json,xml,java)