摘抄的ObjectMapper用法

ObjectMapper使用小例子:

首先有个实体对象:

 
   
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private int age;
private String[] list;
private Date datetime;
<.....省略set get.....>
}

先创建个对象

      static ObjectMapper omapper = new ObjectMapper();

一、对象转换为json数据

    1.  User u = new User();
     u.setAge(24);
     u.setUsername("dobble");
     omapper.writeValue(new File("D:/aa.txt"), u);//写到文件中
     omapper.writeValue(System.out, u);//输出到控制台
        
        输出:{"username":"dobble","age":24,"list":null,"datetime":null}

    2.  List list=new ArrayList();
     list.add(1);
     list.add(2);
     list.add(3);
     String result = omapper.writeValueAsString(list);//序列化
     System.out.println(result);

        输出:[1,2,3]

    3.  omapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);<1>

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");<2>
        omapper.setDateFormat(df);

        User uu = new User();
     uu.setAge(24);
     uu.setDatetime(new Date());
     String[] sts = {"a1","a2","a3"};
     uu.setList(sts);
     uu.setUsername("json");
        String r1 = omapper.writeValueAsString(uu);
     System.out.println(r1);
        
        输出1:不加时间格式为-------{"username":"json","age":24,"list":["a1","a2","a3"],"datetime":1463552017876}
               加了设置<1>为--------{"username":"json","age":24,"list":["a1","a2","a3"],"datetime":"2016-05-18T06:26:13.414+0000"}
               加了自定义<<2>格式为-{"username":"json","age":24,"list":["a1","a2","a3"],"datetime":"2016-05-18 02:30:51"}

    4.  JsonGenerator jg = omapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
     jg.writeObject(uu); //用的是例3的uu对象
     System.out.println();

        输出:加了时间格式---{"username":"json","age":24,"list":["a1","a2","a3"],"datetime":"2016-05-18 02:36:46"}
 

2.json数据转换为对象

        File ff = new File("D:/aa.txt");
        String str = FileUtils.readFileToString(ff);//可以直接读文件 文件中为json数据
//        String jsonStr = "{\"username\":\"misty\",\"age\":\"24\"}";//也可以自己写json数据
        User user = omapper.readValue(str, User.class);
        System.out.println(user.getAge()+"--"+user.getUsername());   
        
 
  
        输出为:24--dobble

获取复杂json数据的特定数据:
        String test="{"results":[
                     {"objectID":357,"geoPoints":[{"x":504604.59802246094,"y":305569.9150390625}]},
                     {"objectID":358,"geoPoints":[{"x":504602.2680053711,"y":305554.43603515625}]}
                     ]}";//双引号要加转义字符,为了方便可以放到文件中读取

        String test = FileUtils.readFileToString(new File("D:/aa.txt")); //将上面字符串放到aa.txt中                                  
        JsonNode jnode = omapper.readTree(test);
     JsonNode node = jnode.get("results");
     for(int i=0;i


你可能感兴趣的:(摘抄的ObjectMapper用法)