Jackson库中objectMapper的使用详解

ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构,反之亦然。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。

构造函数
S.N. 构造函数 & 描述
1 ObjectMapper()
默认的构造函数,这将构建默认JsonFactory必要时使用StdSerializerProvider作为其SerializerProvider,并BeanSerializerFactory作为其SerializerFactory。
2 ObjectMapper(JsonFactory jf)
构造使用指定的JsonFactory构建必要的JsonParsers和/或JsonGenerators映射。
3 ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp)
4 ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp, SerializationConfig sconfig, DeserializationConfig dconfig)
5 ObjectMapper(SerializerFactory sf)
不推荐使用。使用其他构造来代替; 注意,可以设置序列化工厂setSerializerFactory(org.codehaus.jackson.map.SerializerFactory)

示例代码:

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+ " ]";
   }    
}

其中
Student student = mapper.readValue(jsonString, Student.class);
是将string串转化为对象

jsonString = mapper.writeValueAsString(student);
是将对象转化为json格式的字符串。

验证输出

Student [ name: Mahesh, age: 21 ]
{
  "name" : "Mahesh",
  "age" : 21
}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页