@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>
相关推荐
皮皮林5512 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河2 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程5 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅7 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者8 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺8 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart9 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP10 小时前
MyBatis-mybatis入门与增删改查
java
孟陬13 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端