Java教程

java对象和json的相互转换--(1) 使用@JsonSerialize对javabean进行json格式化

本文主要是介绍java对象和json的相互转换--(1) 使用@JsonSerialize对javabean进行json格式化,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

java对象和json的相互转换--(1) 使用@JsonSerialize对javabean进行json格式化
https://blog.csdn.net/wslyk606/article/details/80301782

以json格式输出数据是常用的方式,这次记录下项目中使用的json格式化方法,

使用的jar包为com.fasterxml.jackson.core:jackson-databind,对应的maven依赖为      

 <dependency>

            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.2</version>

        </dependency>

1 首先定义一个Student类

public class Student {    private String name;    private int age;    private int number;     public String getName() {        return name;    }     public int getAge() {        return age;    }     public int getNumber() {        return number;    }     public Student(String name, int age, int number) {         this.name = name;        this.age = age;        this.number = number;    }}

2 定义一个要格式化的类 StudentsReport,使用@JsonSerialize进行格式化,对应的格式化类为 StudentsReportSerializer

import com.fasterxml.jackson.databind.annotation.JsonSerialize;  import java.util.List; import static com.google.common.collect.Lists.newArrayList; @JsonSerialize(using = StudentsReportSerializer.class)public class StudentsReport {    List<String> names = newArrayList();    List<Student> studentList = newArrayList();     public List<String> getNames() {        return names;    }     public List<Student> getStudentList() {        return studentList;    }     public StudentsReport(List<String> names, List<Student> studentList) {         this.names = names;        this.studentList = studentList;    }}


3  对应的格式化的类为

import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public class StudentsReportSerializer extends JsonSerializer <StudentsReport>{@Override    public void serialize(StudentsReport studentsReport, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {        jgen.writeStartObject(); //start write :"{"         jgen.writeFieldName("studentsName");        jgen.writeStartArray();// write "["        for (String name:studentsReport.getNames()             ) {            jgen.writeObject(name);        }        jgen.writeEndArray();          jgen.writeFieldName("studentsData");        jgen.writeStartArray();        for (Student student : studentsReport.getStudentList()){            jgen.writeStartObject();             jgen.writeStringField("name",student.getName());            jgen.writeNumberField("age",16);            jgen.writeNumberField("number",1);             jgen.writeEndObject();        }        jgen.writeEndArray();         jgen.writeEndObject();  //end :"}"    } }
 4 进行测试

import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; import static com.google.common.collect.Lists.newArrayList; public class TestJson {    public static void main(String[] args) throws JsonProcessingException {        Student student1 = new Student("Tom",16,1);        Student student2 = new Student("Jerry",17,2);        List<Student> studentList = newArrayList();        studentList.add(student1);        studentList.add(student2);         List<String> studentsName = newArrayList(student1.getName(),student2.getName());           StudentsReport report = new StudentsReport(studentsName,studentList);         ObjectMapper mapper = new ObjectMapper();         String jsonReport = mapper.writeValueAsString(report);         System.out.println(jsonReport);     }}

输出结果为   {"studentsName":["Tom","Jerry"],"studentsData":[{"name":"Tom","age":16,"number":1},{"name":"Jerry","age":16,"number":1}]}

即 :{
    "studentsName":[
        "Tom",
        "Jerry"
    ],
    "studentsData":[
        {
            "name":"Tom",
            "age":16,
            "number":1
        },
        {
            "name":"Jerry",
            "age":16,
            "number":1
        }
    ]
}

ps:使用的newArrayList()是使用了com.google.guava这个包,对应的maven依赖为

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>12.0.1</version>
        </dependency>




这篇关于java对象和json的相互转换--(1) 使用@JsonSerialize对javabean进行json格式化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!