举例讲解Java的Jackson库中ObjectMapper类的使用

 更新时间:2016年01月13日 12:03:45   投稿:goldensun  
这篇文章主要介绍了举例讲解Java的Jackson库中ObjectMapper类的使用,Jackson库通常被用来实现Java的对象和JSON之间的转换功能,需要的朋友可以参考下

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

类声明
以下是org.codehaus.jackson.map.ObjectMapper类的声明:

public class ObjectMapper
  extends ObjectCodec
   implements Versioned

嵌套类

S.N. 类 & 描述
1 static class ObjectMapper.DefaultTypeResolverBuilder//定制TypeResolverBuilder,提供所谓的“默认输入”使用类型解析构建器(见enableDefaultTyping()了解详细信息)。
2 static class ObjectMapper.DefaultTyping//使用enableDefaultTyping()枚举指定什么样的类型(类)默认输入应该使用。

构造函数
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)

这个类继承了以下类方法:
java.lang.Object

例子
测试类基本代码如下

/* 
 * @project java 
 * @package 
 * @file Jackson.java 
 * @version 1.0 

 */ 
 
public class Jackson { 
  /* 
   * 
   * Class Descripton goes here. 
   * 
   * @class Jackson 
   * @version 1.0 
   */ 
  public static JsonGenerator jsonGenerator = null; 
  private static ObjectMapper mapper = new ObjectMapper(); 
  public static void main(String[] args) { 
    Student student = new Student(); 
    student.setIsstudent(true); 
    student.setUid(1000); 
    student.setUname("xiao liao"); 
    student.setUpwd("123"); 
    student.setNumber(12); 
     
    Map<String, Student> stuMap = new HashMap<String, Student>(); 
    stuMap.put("1", student); 
    stuMap.put("2", student); 
     
    List<Object> stuList = new ArrayList<Object>(); 
    List<Student> stuList1 = new ArrayList<Student>(); 
    stuList1.add(student); 
    student= new Student(); 
    student.setIsstudent(false); 
    student.setUid(200); 
    student.setUname("xiao mi"); 
    stuList1.add(student); 
     
    stuList.add(student); 
    stuList.add("xiao xin"); 
    stuList.add("xiao er"); 
    stuList.add(stuMap); 
     
    //readJson2List(); 
    try { 
      //readJson2Array(); 
      //writeArray2Json(array); 
      //writeJson2List(); 
      //writeEntity2Json(student); 
      writeJson2Entity(); 
      //writeMap2Json(stuMap); 
      //writeList2Json(stuList1); 
       
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
   /** 
   * 
   * <code>writeEntity2Json</code> 
   * @description: TODO(实体类转换成json) 
   * @param object 
   * @throws IOException 
   */ 
   public static void writeEntity2Json(Object object) throws IOException { 
      mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object ); 
      mapper.writeValue( System.out,object ); 
      
   } 
   /** 
   * 
   * <code>writeArray2Json</code> 
   * @description: TODO(数组转换成json数组) 
   * @param object 
   * @throws IOException 
   */ 
   public static void writeArray2Json(Object object) throws IOException { 
      
     // writeValue具有和writeObject相同的功能 
     mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object ); 
     mapper.writeValue(System.out,object ); 
      
   } 
   /** 
   * 
   * <code>writeMap2Json</code> 
   * @description: TODO(map对象转换成json对象) 
   * @param object 
   * @throws IOException 
   * @since  2011-11-8   廖益平 
   */ 
   public static void writeMap2Json(Object object) throws IOException { 
      
     System.out.println("使用ObjectMapper-----------"); 
     // writeValue具有和writeObject相同的功能 
     System.out.println("==>"+mapper.writeValueAsString(object)); 
     mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object ); 
     mapper.writeValue( System.out , object ); 
   } 
   /** 
   * 
   * <code>writeList2Json</code> 
   * @description: TODO(list转换成json) 
   * @param object 
   * @throws IOException 
   */ 
   public static void writeList2Json(Object object) throws IOException { 
     System.out.println("==>"+mapper.writeValueAsString(object)); 
     mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object ); 
     mapper.writeValue( System.out , object ); 
   } 
   /** 
   * 
   * <code>writeJson2Entity</code> 
   * @description: TODO(json转换成实体) 
   * @throws IOException 
   */ 
   public static void writeJson2Entity() throws IOException { 
     System.out.println("json串转换成entity-------------"); 
//    File file = new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"); 
//    FileInputStream inputStream = new FileInputStream(file); 
//    Student student = mapper.readValue(inputStream,Student.class); 
//    System.out.println(student.toString()); 
     //漂亮输出 
     //mapper.defaultPrettyPrintingWriter().writeValueAsString(value); 
   
     String json = "{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true}"; 
     Student student1 = mapper.readValue(json,Student.class); 
     System.out.println("json2:"+student1.toString()); 
   } 
   /** 
   * 
   * <code>writeJson2List</code> 
   * @description: TODO(json专程list对象) 
   * @throws IOException 
   */ 
   public static void writeJson2List() throws IOException { 
     System.out.println("json串转换成entity-------------"); 
     File file = new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"); 
     FileInputStream inputStream = new FileInputStream(file); 
     Student student = mapper.readValue(inputStream,Student.class); 
     System.out.println(student.toString()); 
      
     String json = "[{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true},{\"uid\":200,\"uname\":\"xiao mi\",\"upwd\":null,\"number\":0.0,\"isstudent\":false}]"; 
     List<LinkedHashMap<String, Object>> s= mapper.readValue(json,List.class); 
     for (int i = 0; i < s.size(); i++) { 
       LinkedHashMap<String, Object> link = s.get(i); 
       Set<String> key = link.keySet(); 
       for (Iterator iterator = key.iterator(); iterator.hasNext();) { 
        String string = (String) iterator.next(); 
        System.out.println(string+"==>"+link.get(string)); 
         
      } 
       System.out.println("json:"+i+""+s.get(i).toString()); 
       
    } 
   } 
   /** 
    * JSON转换为List对象 
    */ 
   public static void readJson2List() { 
    String json = "[{\"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 (int i = 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();) { 
     String key = it.next(); 
     System.out.println(key + ":" + map.get(key)); 
     } 
    } 
    } catch (JsonParseException e) { 
    e.printStackTrace(); 
    } catch (JsonMappingException e) { 
    e.printStackTrace(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
   } 
   /** 
    * JSON转换为List对象 
    */ 
   public static void readJson2Array() { 
     String json = "[{\"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 (Student student : students) { 
        System.out.println(">"+student.toString()); 
      } 
     } catch (JsonParseException e) { 
       e.printStackTrace(); 
     } catch (JsonMappingException e) { 
       e.printStackTrace(); 
     } catch (IOException e) { 
       e.printStackTrace(); 
     } 
   } 
 
} 

打印结果 :

串转换成entity-------------
json2:uid=1000,name=xiao liao,upwd=123,number=12.0,isStudent=true

writeMap2Json -----------
{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","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":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}

大家逐个自己试试吧  ,上面也是我的测试代码

相关文章

  • Java中的Vector和Stack底层源码分析

    Java中的Vector和Stack底层源码分析

    这篇文章主要介绍了Java中的Vector和Stack底层源码分析,Stack继承了Vector,Vector底层还是一个List,也就是基于数组来实现的,所以ArrayList有的优点,比如获取元素的速度快,随机读,它都有,需要的朋友可以参考下
    2023-12-12
  • springmvc配置线程池Executor做多线程并发操作的代码实例

    springmvc配置线程池Executor做多线程并发操作的代码实例

    今天小编就为大家分享一篇关于springmvc配置线程池Executor做多线程并发操作的代码实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-03-03
  • 使用Java和WebSocket实现网页聊天室实例代码

    使用Java和WebSocket实现网页聊天室实例代码

    WebSocket是HTML5一种新的协议,它实现了浏览器与服务器全双工通信,这里就将使用WebSocket来开发网页聊天室,对Java和WebSocket实现网页聊天室的实例代码感兴趣的朋友一起学习吧
    2016-06-06
  • Spring Bean的实例化之属性注入源码剖析过程

    Spring Bean的实例化之属性注入源码剖析过程

    本篇文章主要就是分析Spring源码剖析-Bean的实例化-属性注入的相关知识,通过本文学习AbstractAutowireCapableBeanFactory#populateBean 方法的主要功能就是属性填充,感兴趣的朋友跟随小编一起看看吧
    2021-06-06
  • Mybatis的mapper.xml中if标签test判断的用法说明

    Mybatis的mapper.xml中if标签test判断的用法说明

    这篇文章主要介绍了Mybatis的mapper.xml中if标签test判断的用法说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • Java使用Soap方式调用WebService接口代码示例

    Java使用Soap方式调用WebService接口代码示例

    Java调用WebService接口是指通过Java语言来访问并与WebService进行交互,WebService是一种基于Web的服务架构,它通过标准的XML和HTTP协议来提供服务,这篇文章主要给大家介绍了关于Java使用Soap方式调用WebService接口的相关资料,需要的朋友可以参考下
    2024-03-03
  • Java数字格式类(NumberFormat类和DecimalFormat类)用法详解

    Java数字格式类(NumberFormat类和DecimalFormat类)用法详解

    NumberFormat类是Java提供的一个格式化数字的类,可以将一串数字转化成自己想要的数据格式,也可以将字符串转化成数值,下面这篇文章主要给大家介绍了关于Java数字格式类(NumberFormat类和DecimalFormat类)用法的相关资料,需要的朋友可以参考下
    2022-07-07
  • SpringMVC中转发与重定向的区别浅析

    SpringMVC中转发与重定向的区别浅析

    这篇文章主要给大家介绍了关于SpringMVC中转发与重定向的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • JDK动态代理步骤详解(源码分析)

    JDK动态代理步骤详解(源码分析)

    这篇文章主要介绍了JDK动态代理步骤详解,首先需要创建一个实现接口InvocationHandler的类,它必须实现invoke方法 ,最后通过Proxy的静态方法实现此操作,需要的朋友可以参考下
    2021-06-06
  • Spring Boot优雅使用RocketMQ的方法实例

    Spring Boot优雅使用RocketMQ的方法实例

    这篇文章主要给大家介绍了关于Spring Boot优雅使用RocketMQ的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring Boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-12-12

最新评论