jackson框架 json字符串、map、java对象的转换例子
先下载框架jar包:
下面是一些例子:
package jackson;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.junit.Test;
public class Testjackson {
//@Test
public void test1(){
try{
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
//json字符串转对象
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
//对象转json字符串
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
//json字符串转为Map对象
Map map=mapper.readValue(jsonString, Map.class);
System.out.println(map);
}catch(Exception e) {
e.printStackTrace();
}
}
//@Test
public void test2(){
try{
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
ObjectMapper mapper = new ObjectMapper();
//将Java对象序列化到一个JSON文件
mapper.writeValue(new File("d:/student.json"), student);
System.out.println("d:/student.json文件生成结束");
//读取JSON文件转换为对象
Student student2 = mapper.readValue(new File("student.json"), Student.class);
System.out.println(student2);
}catch(Exception e) {
e.printStackTrace();
}
}
//@Test
public void test3(){
try {
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> studentDataMap = new HashMap<String,Object>();
int[] marks = {1,2,3};
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
studentDataMap.put("student", student);
studentDataMap.put("name", "Mahesh Kumar");
studentDataMap.put("verified", Boolean.FALSE);
studentDataMap.put("marks", marks);
//Map转换为joson文件
mapper.writeValue(new File("d:/student2.json"), studentDataMap);
//result student.json
//{
// "student":{"name":"Mahesh","age":10},
// "marks":[1,2,3],
// "verified":false,
// "name":"Mahesh Kumar"
//}
//json文件转换为map
studentDataMap = mapper.readValue(new File("d:/student2.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 (Exception e) {
e.printStackTrace();
}
}
//@Test//树遍历
public void test4(){
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}";
JsonNode rootNode = mapper.readTree(jsonString);
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 marksNode = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode.getElements();
System.out.print("Marks: [ ");
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.getIntValue() + " ");
}
System.out.println("]");
} catch (Exception e) {
e.printStackTrace();
}
}
//@Test//树到JSON转换
public void test5(){
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("d:/student3.json"), rootNode);
rootNode = mapper.readTree(new FileInputStream("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 (Exception e) {
e.printStackTrace();
}
}
//@Test//树到java对象
public void test6(){
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 FileInputStream("student.json"));
Student2 student = mapper.treeToValue(rootNode, Student2.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 (Exception e) {
e.printStackTrace();
}
}
@Test//Jackson流式API
public void test7(){
try {
JsonFactory jasonFactory = new JsonFactory();
JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(new File("d:/student7.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]
//}
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> dataMap = mapper.readValue(new File("d:/student7.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 (Exception e) {
e.printStackTrace();
}
}
@Test//使用JsonParser 读取JSON
public void test8(){
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("d:/student7.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 (Exception e) {
e.printStackTrace();
}
}
}
class Student2 {
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;
}
}