jackson在springboot的使用
1.1 各种注解的使用
1.2 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1.3 通过访问controller,然后进行静态页面的跳转
jackson基础转载自
2.1 jackson基本实现类:ObjectMapper
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class JacksonTester {
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//map json to student
try {
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
2.2 将json序列化到文件以及反序列化
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
tester.writeJSON(student);
Student student1 = tester.readJSON();
System.out.println(student1);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("student.json"), student);
}
private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue(new File("student.json"), Student.class);
return student;
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
2.3 json数据与java类型之间的转换
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
//创建map
Map<String,Object> studentDataMap = new HashMap<String,Object>();
//创建数组
int[] marks = {1,2,3};
//创建学生对象
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
// JAVA Object
studentDataMap.put("student", student);
// JAVA String
studentDataMap.put("name", "Mahesh Kumar");
// JAVA Boolean
studentDataMap.put("verified", Boolean.FALSE);
// Array
studentDataMap.put("marks", marks);
mapper.writeValue(new File("student.json"), studentDataMap);
//result student.json
//{
// "student":{"name":"Mahesh","age":10},
// "marks":[1,2,3],
// "verified":false,
// "name":"Mahesh Kumar"
//}
studentDataMap = mapper.readValue(new File("student.json"), Map.class);
System.out.println(studentDataMap.get("student"));
System.out.println(studentDataMap.get("name"));
System.out.println(studentDataMap.get("verified"));
System.out.println(studentDataMap.get("marks"));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
2.4 json全数据绑定
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
tester.writeJSON(student);
Student student1 = tester.readJSON();
System.out.println(student1);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("student.json"), student);
}
private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue(new File("student.json"), Student.class);
return student;
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
2.5 Jackson数据绑定泛型
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
Map userDataMap = new HashMap();
UserData studentData = new UserData();
int[] marks = {1,2,3};
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
// JAVA Object
studentData.setStudent(student);
// JAVA String
studentData.setName("Mahesh Kumar");
// JAVA Boolean
studentData.setVerified(Boolean.FALSE);
// Array
studentData.setMarks(marks);
TypeReference ref = new TypeReference>() { };
userDataMap.put("studentData1", studentData);
mapper.writeValue(new File("student.json"), userDataMap);
//{
// "studentData1":
// {
// "student":
// {
// "name":"Mahesh",
// "age":10
// },
// "name":"Mahesh Kumar",
// "verified":false,
// "marks":[1,2,3]
// }
//}
userDataMap = mapper.readValue(new File("student.json"), ref);
System.out.println(userDataMap.get("studentData1").getStudent());
System.out.println(userDataMap.get("studentData1").getName());
System.out.println(userDataMap.get("studentData1").getVerified());
System.out.println(Arrays.toString(userDataMap.get("studentData1").getMarks()));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
class UserData {
private Student student;
private String name;
private Boolean verified;
private int[] marks;
public UserData(){}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public int[] getMarks() {
return marks;
}
public void setMarks(int[] marks) {
this.marks = marks;
}
}
2.6 json可创建一颗树并返回根节点
//Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
//create tree from JSON
JsonNode rootNode = mapper.readTree(jsonString);
// 遍历模型
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.getTextValue());
JsonNode marksNode = rootNode.path("marks");
Iterator iterator = marksNode.getElements();
2.6.1 树到JSON转换
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
JsonNode marksNode = mapper.createArrayNode();
((ArrayNode)marksNode).add(100);
((ArrayNode)marksNode).add(90);
((ArrayNode)marksNode).add(85);
((ObjectNode) rootNode).put("name", "Mahesh Kumar");
((ObjectNode) rootNode).put("age", 21);
((ObjectNode) rootNode).put("verified", false);
((ObjectNode) rootNode).put("marks",marksNode);
mapper.writeValue(new File("student.json"), rootNode);
rootNode = mapper.readTree(new File("student.json"));
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.getTextValue());
JsonNode ageNode = rootNode.path("age");
System.out.println("Age: " + ageNode.getIntValue());
JsonNode verifiedNode = rootNode.path("verified");
System.out.println("Verified: " + (verifiedNode.getBooleanValue() ? "Yes":"No"));
JsonNode marksNode1 = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode1.getElements();
System.out.print("Marks: [ ");
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.getIntValue() + " ");
}
System.out.println("]");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.6.2 从树到Java对象转换
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
JsonNode marksNode = mapper.createArrayNode();
((ArrayNode)marksNode).add(100);
((ArrayNode)marksNode).add(90);
((ArrayNode)marksNode).add(85);
((ObjectNode) rootNode).put("name", "Mahesh Kumar");
((ObjectNode) rootNode).put("age", 21);
((ObjectNode) rootNode).put("verified", false);
((ObjectNode) rootNode).put("marks",marksNode);
mapper.writeValue(new File("student.json"), rootNode);
rootNode = mapper.readTree(new File("student.json"));
Student student = mapper.treeToValue(rootNode, Student.class);
System.out.println("Name: "+ student.getName());
System.out.println("Age: " + student.getAge());
System.out.println("Verified: " + (student.isVerified() ? "Yes":"No"));
System.out.println("Marks: "+Arrays.toString(student.getMarks()));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
int age;
boolean verified;
int[] marks;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
public int[] getMarks() {
return marks;
}
public void setMarks(int[] marks) {
this.marks = marks;
}
}
2.7 流式API
2.7.1 写入
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
JsonFactory jasonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(new File(
"student.json"), JsonEncoding.UTF8);
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField("name", "Mahesh Kumar");
// "age" : 21
jsonGenerator.writeNumberField("age", 21);
// "verified" : false
jsonGenerator.writeBooleanField("verified", false);
// "marks" : [100, 90, 85]
jsonGenerator.writeFieldName("marks");
// [
jsonGenerator.writeStartArray();
// 100, 90, 85
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
// ]
jsonGenerator.writeEndArray();
// }
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> dataMap = mapper.readValue(new File("student.json"), Map.class);
System.out.println(dataMap.get("name"));
System.out.println(dataMap.get("age"));
System.out.println(dataMap.get("verified"));
System.out.println(dataMap.get("marks"));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.7.2 使用JsonParser 读取JSON
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
JsonFactory jasonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(new File(
"student.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Mahesh Kumar");
jsonGenerator.writeNumberField("age", 21);
jsonGenerator.writeBooleanField("verified", false);
jsonGenerator.writeFieldName("marks");
jsonGenerator.writeStartArray(); // [
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
JsonParser jsonParser = jasonFactory.createJsonParser(new File("student.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
//get the current token
String fieldname = jsonParser.getCurrentName();
if ("name".equals(fieldname)) {
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
if("age".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getNumberValue());
}
if("verified".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getBooleanValue());
}
if("marks".equals(fieldname)){
//move to [
jsonParser.nextToken();
// loop till token equal to "]"
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
System.out.println(jsonParser.getNumberValue());
}
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
转载来源:https://blog.csdn.net/srj1095530512/article/details/82529759
这个文章 fastjson讲的很清楚,而且有对应的源码分析,我就不多加总结了,有兴趣的小哥可以去看看。
下面只是单纯取出测试类以及测试代码
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
public class MyJson {
public static void main(String[] args) {
List<Student> list=new ArrayList<>();
Student student=new Student("bob",24);
Student student12=new Student("lily", 23);
list.add(student);
list.add(student12);
System.out.println("*******javaBean to jsonString*******");
String str1=JSON.toJSONString(student);
System.out.println(str1);
System.out.println(JSON.toJSONString(list));
System.out.println();
System.out.println("******jsonString to javaBean*******");
//Student stu1=JSON.parseObject(str1,new TypeReference(){});
Student stu1=JSON.parseObject(str1,Student.class);
System.out.println(stu1);
System.out.println();
System.out.println("******javaBean to jsonObject******");
JSONObject jsonObject1=(JSONObject)JSON.toJSON(student);
System.out.println(jsonObject1.getString("name"));
System.out.println();
System.out.println("******jsonObject to javaBean******");
Student student2=JSON.toJavaObject(jsonObject1, Student.class);
System.out.println(student2);
System.out.println();
System.out.println("*******javaBean to jsonArray******");
List<Student> stulist=new ArrayList<>();
for(int i=0;i<5;i++){
stulist.add(new Student("student"+i, i));
}
JSONArray jsonArrays=(JSONArray)JSON.toJSON(stulist);
for(int i=0;i<jsonArrays.size();i++){
System.out.println(jsonArrays.getJSONObject(i));
}
System.out.println();
System.out.println("*****jsonArry to javalist******");
List<Student> myList=new ArrayList<>();
for(int i=0;i<jsonArrays.size();i++){
Student student3=JSON.toJavaObject(jsonArrays.getJSONObject(i), Student.class);
myList.add(student3);
}
for(Student stu:myList){
System.out.println(stu);
}
System.out.println();
System.out.println("*****jsonObject to jsonString*****");
String str4=JSON.toJSONString(jsonObject1);
System.out.println(str4);
System.out.println();
System.out.println("*******jsonString to jsonObject*****");
JSONObject jso1=JSON.parseObject(str1);
System.out.println(jso1.getString("name"));
System.out.println();
System.out.println("*****jsonString to jsonArray*****");
JSONArray jArray=JSON.parseArray(JSON.toJSONString(stulist));
for(int i=0;i<jArray.size();i++){
System.out.println(jArray.getJSONObject(i));
}
System.out.println();
}
}
public class Student {
private String name;
private int age;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "student [name="+name+" , "+"age="+age+"]";
}