举例讲解Java的Jackson库中ObjectMapper类的使用
ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构,反之亦然。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。
类声明
以下是org.codehaus.jackson.map.ObjectMapper类的声明:
publicclassObjectMapper extendsObjectCodec implementsVersioned
嵌套类
| S.N. | 类&描述 |
|---|---|
| 1 | staticclassObjectMapper.DefaultTypeResolverBuilder//定制TypeResolverBuilder,提供所谓的“默认输入”使用类型解析构建器(见enableDefaultTyping()了解详细信息)。 |
| 2 | staticclassObjectMapper.DefaultTyping//使用enableDefaultTyping()枚举指定什么样的类型(类)默认输入应该使用。 |
构造函数
| S.N. | 构造函数&描述 |
|---|---|
| 1 | ObjectMapper()//默认的构造函数,这将构建默认JsonFactory必要时使用StdSerializerProvider作为其SerializerProvider,并BeanSerializerFactory作为其SerializerFactory。 |
| 2 | ObjectMapper(JsonFactoryjf)//构造使用指定的JsonFactory构建必要的JsonParsers和/或JsonGenerators映射。 |
| 3 | ObjectMapper(JsonFactoryjf,SerializerProvidersp,DeserializerProviderdp) |
| 4 | ObjectMapper(JsonFactoryjf,SerializerProvidersp,DeserializerProviderdp,SerializationConfigsconfig,DeserializationConfigdconfig) |
| 5 | ObjectMapper(SerializerFactorysf)不推荐使用。使用其他构造来代替;注意,可以设置序列化工厂setSerializerFactory(org.codehaus.jackson.map.SerializerFactory) |
这个类继承了以下类方法:
java.lang.Object
例子
测试类基本代码如下
/*
*@projectjava
*@package
*@fileJackson.java
*@version1.0
*/
publicclassJackson{
/*
*
*ClassDescriptongoeshere.
*
*@classJackson
*@version1.0
*/
publicstaticJsonGeneratorjsonGenerator=null;
privatestaticObjectMappermapper=newObjectMapper();
publicstaticvoidmain(String[]args){
Studentstudent=newStudent();
student.setIsstudent(true);
student.setUid(1000);
student.setUname("xiaoliao");
student.setUpwd("123");
student.setNumber(12);
Map<String,Student>stuMap=newHashMap<String,Student>();
stuMap.put("1",student);
stuMap.put("2",student);
List<Object>stuList=newArrayList<Object>();
List<Student>stuList1=newArrayList<Student>();
stuList1.add(student);
student=newStudent();
student.setIsstudent(false);
student.setUid(200);
student.setUname("xiaomi");
stuList1.add(student);
stuList.add(student);
stuList.add("xiaoxin");
stuList.add("xiaoer");
stuList.add(stuMap);
//readJson2List();
try{
//readJson2Array();
//writeArray2Json(array);
//writeJson2List();
//writeEntity2Json(student);
writeJson2Entity();
//writeMap2Json(stuMap);
//writeList2Json(stuList1);
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*
*<code>writeEntity2Json</code>
*@description:TODO(实体类转换成json)
*@paramobject
*@throwsIOException
*/
publicstaticvoidwriteEntity2Json(Objectobject)throwsIOException{
mapper.writeValue(newFile("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object);
mapper.writeValue(System.out,object);
}
/**
*
*<code>writeArray2Json</code>
*@description:TODO(数组转换成json数组)
*@paramobject
*@throwsIOException
*/
publicstaticvoidwriteArray2Json(Objectobject)throwsIOException{
//writeValue具有和writeObject相同的功能
mapper.writeValue(newFile("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object);
mapper.writeValue(System.out,object);
}
/**
*
*<code>writeMap2Json</code>
*@description:TODO(map对象转换成json对象)
*@paramobject
*@throwsIOException
*@since2011-11-8廖益平
*/
publicstaticvoidwriteMap2Json(Objectobject)throwsIOException{
System.out.println("使用ObjectMapper-----------");
//writeValue具有和writeObject相同的功能
System.out.println("==>"+mapper.writeValueAsString(object));
mapper.writeValue(newFile("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object);
mapper.writeValue(System.out,object);
}
/**
*
*<code>writeList2Json</code>
*@description:TODO(list转换成json)
*@paramobject
*@throwsIOException
*/
publicstaticvoidwriteList2Json(Objectobject)throwsIOException{
System.out.println("==>"+mapper.writeValueAsString(object));
mapper.writeValue(newFile("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object);
mapper.writeValue(System.out,object);
}
/**
*
*<code>writeJson2Entity</code>
*@description:TODO(json转换成实体)
*@throwsIOException
*/
publicstaticvoidwriteJson2Entity()throwsIOException{
System.out.println("json串转换成entity-------------");
//Filefile=newFile("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt");
//FileInputStreaminputStream=newFileInputStream(file);
//Studentstudent=mapper.readValue(inputStream,Student.class);
//System.out.println(student.toString());
//漂亮输出
//mapper.defaultPrettyPrintingWriter().writeValueAsString(value);
Stringjson="{\"uid\":1000,\"uname\":\"xiaoliao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true}";
Studentstudent1=mapper.readValue(json,Student.class);
System.out.println("json2:"+student1.toString());
}
/**
*
*<code>writeJson2List</code>
*@description:TODO(json专程list对象)
*@throwsIOException
*/
publicstaticvoidwriteJson2List()throwsIOException{
System.out.println("json串转换成entity-------------");
Filefile=newFile("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt");
FileInputStreaminputStream=newFileInputStream(file);
Studentstudent=mapper.readValue(inputStream,Student.class);
System.out.println(student.toString());
Stringjson="[{\"uid\":1000,\"uname\":\"xiaoliao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true},{\"uid\":200,\"uname\":\"xiaomi\",\"upwd\":null,\"number\":0.0,\"isstudent\":false}]";
List<LinkedHashMap<String,Object>>s=mapper.readValue(json,List.class);
for(inti=0;i<s.size();i++){
LinkedHashMap<String,Object>link=s.get(i);
Set<String>key=link.keySet();
for(Iteratoriterator=key.iterator();iterator.hasNext();){
Stringstring=(String)iterator.next();
System.out.println(string+"==>"+link.get(string));
}
System.out.println("json:"+i+""+s.get(i).toString());
}
}
/**
*JSON转换为List对象
*/
publicstaticvoidreadJson2List(){
Stringjson="[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"
+"{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";
try{
List<LinkedHashMap<String,Object>>list=mapper.readValue(
json,List.class);
System.out.println(list.size());
for(inti=0;i<list.size();i++){
Map<String,Object>map=list.get(i);
Set<String>set=map.keySet();
for(Iterator<String>it=set.iterator();it.hasNext();){
Stringkey=it.next();
System.out.println(key+":"+map.get(key));
}
}
}catch(JsonParseExceptione){
e.printStackTrace();
}catch(JsonMappingExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*JSON转换为List对象
*/
publicstaticvoidreadJson2Array(){
Stringjson="[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"
+"{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";
try{
Student[]students=mapper.readValue(json,Student[].class);
for(Studentstudent:students){
System.out.println(">"+student.toString());
}
}catch(JsonParseExceptione){
e.printStackTrace();
}catch(JsonMappingExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
打印结果:
串转换成entity-------------
json2:uid=1000,name=xiaoliao,upwd=123,number=12.0,isStudent=true
writeMap2Json-----------
{"2":{"uid":1000,"uname":"xiaoliao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiaoliao","upwd":"123","number":12.0,"isstudent":true}}
readJson2Array------------------
>uid=1,name=www,upwd=456,number=234.0,isStudent=false
>uid=5,name=tom,upwd=123,number=3.44,isStudent=false
writeMap2Json-----------
{"2":{"uid":1000,"uname":"xiaoliao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiaoliao","upwd":"123","number":12.0,"isstudent":true}}
大家逐个自己试试吧 ,上面也是我的测试代码