1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public class JacksonTest {
@Test public void test1() throws JsonGenerationException, JsonMappingException, IOException { Product p = new Product(); p.setId(1); p.setName("电视机"); p.setPrice(2000); p.setReleaseDate(new Date());
ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); String json = mapper.writeValueAsString(p); System.out.println(json); Product p1 = mapper.readValue(json, Product.class); System.out.println(p1.getName()); }
@Test public void test2() throws JsonGenerationException, JsonMappingException, IOException { Product p1 = new Product(); p1.setId(1); p1.setName("电视机"); p1.setPrice(2000);
Product p2 = new Product(); p2.setId(2); p2.setName("电冰箱"); p2.setPrice(3000);
List<Product> ps = new ArrayList<Product>(); ps.add(p1); ps.add(p2);
ObjectMapper mapper = new ObjectMapper();
FilterProvider fp = new SimpleFilterProvider().addFilter("productFilter", SimpleBeanPropertyFilter.filterOutAllExcept("id", "name"));
mapper.setFilters(fp);
String json = mapper.writeValueAsString(ps); System.out.println(json); JavaType javaType = getCollectionType(ArrayList.class, Product.class); List<Product> ps1 = (List<Product>) mapper.readValue(json, javaType); System.out.println(ps1.get(0).getName()); }
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { ObjectMapper mapper = new ObjectMapper(); return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); } }
|