一、用ObjectMapper.readValue(jsonString, Student.class) , ObjectMapper.writeValueAsString(student)
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对象。它是一个可重复使用的对象。 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+ " ]"; } }
二、将Java对象序列化到一个JSON文件,然后再读取JSON文件获取转换为对象。在这个例子中,创建了Student类。创建将有学生对象以JSON表示在一个student.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 JacksonTester2 { public static void main(String args[]){ JacksonTester2 tester = new JacksonTester2(); 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(); } } //这里将介绍将Java对象序列化到一个JSON文件,然后再读取JSON文件获取转换为对象。 //在这个例子中,创建了Student类。创建将有学生对象以JSON表示在一个student.json文件。 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; } }
时间: 2024-10-22 01:23:28