@JsonSerialize

在需要序列化为json输出的类上增加@JsonSerialize.

java对象和json的相互转换--

(1) 使用@JsonSerialize对javabean进行json格式化

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

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

javascript 复制代码
 <dependency>

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

1 首先定义一个Student类

javascript 复制代码
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

javascript 复制代码
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 对应的格式化的类为

javascript 复制代码
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 进行测试

javascript 复制代码
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>
相关推荐
靠沿3 小时前
Java数据结构初阶——LinkedList
java·开发语言·数据结构
qq_12498707533 小时前
基于springboot的建筑业数据管理系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·毕业设计
一 乐3 小时前
宠物管理|宠物共享|基于Java+vue的宠物共享管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·springboot·宠物
a crazy day3 小时前
Spring相关知识点【详细版】
java·spring·rpc
白露与泡影3 小时前
MySQL中的12个良好SQL编写习惯
java·数据库·面试
foundbug9994 小时前
配置Spring框架以连接SQL Server数据库
java·数据库·spring
悦悦子a啊4 小时前
项目案例作业(选做):使用文件改造已有信息系统
java·开发语言·算法
lkbhua莱克瓦244 小时前
Java项目——斗地主小游戏(控制台版)
java·开发语言·windows·斗地主项目