实习笔记 6: 测试技巧,json序列化对象

EJB test测试略麻烦啊,不像spring直接有测试框架。

师父推荐了了一个Jackson 序列化对象的jar,挺好用的,分享下。

1. 不仅可以简单的readV

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(new File("user-modified.json") , bill);
            BillInfo read_bill=objectMapper.readValue(new File("user-modified.json"), BillInfo.class);
            System.out.println(read_bill.getBillPrice());

2. 使用注解的方法,继承的时候也可以玩

@JsonCreator // important!
  MixIn(@JsonProperty("width") int w
    w, @JsonProperty("height") int h) {}

  @JsonProperty("width")
  abstract int getW(); // rename
  @JsonProperty("height")
  abstract int getH(); // rename
  @JsonIgnore
   abstract int getSize(); // remove
}

3. 注意转换成list,[],map的时候注意要用convertValue

  List<String> keys = ...;
  String[] keyArray = mapper.convertValue(
    keys, String[].class);
  Map<String,Integer> map = mapper.convertValue(
    pojo, new TypeReference<String,Integer>(){});

4. 没看懂的smile 和 myBean

ObjectMapper m = new ObjectMapper
    (new SmileFactory());
 ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new MrBeanModule());
    Name n = mapper.readValue(in, Name.class);

5. 数据比较多的时候,用了readValues

ObjectReader r = mapper.reader(Point.class);
MappingIterator<Point> it = r.readValues(in);
while (it.hasNextValue()) {
    Point p = it.nextValue();
    // ... process
}

6. JsonValue 和 JsonCreator 主要写在方法前面

7. JsonUnwrapped 出现那种点操作,这样可以不用出现nested的包裹

 

Reference:

https://docs.google.com/presentation/d/1t4VkFUbQK0JeAZLPCn8ZJ5ij0Q0hIqcgWmRHmjGs5eA/edit#slide=id.p

 

 

 

 

posted on 2013-07-28 22:24  surghost  阅读(591)  评论(0编辑  收藏  举报

导航