jackson详解 |
您所在的位置:网站首页 › als官网 › jackson详解 |
java中常见的json解析有json-lib、jackson两种方案,前者是老牌技术,后者在解析大数据的时候性能比较好。现在又出现了很多json解析技术,如:fastjson、gson等。 一、springmvc默认使用的是jackson来解析json的,需要作如下配置: 1)需要用到的包:jackson-core-asl-1.9.12.jar、jackson-mapper-asl-1.9.12.jar 2)在spring的配置文件中有两种办法设置: 方案一: 方案二: text/plain; charset=UTF-8二、jackson使用: 首先去官网下载Jackson工具包,下载地址http://wiki.fasterxml.com/JacksonDownload。Jackson有1.x系列和2.x系列: jackson-core-2.2.3.jar 核心jar包 jackson-annotations-2.2.3.jar注解包(可选),提供注解功能 jackson-databind-2.2.3.jar 数据绑定包(可选),提供基于“对象绑定”和“树模型”相关API。 1、jackson常用功能(即将一个对象序列化为json字符串和将一串json字符串反序列化为java对象或Map): public class Person { private String name; private int age; //set/get方法 } public class Demo { public static void main(String[] args) { // writeJsonObject(); // readJsonObject(); // readJsonMap(); } // 序列化到文件 public static void writeJsonObject() { ObjectMapper mapper = new ObjectMapper(); Person person = new Person("nomouse", 25); try { mapper.writeValue(new File("c:/person.json"), person); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 直接将一个json转化为对象 public static void readJsonObject() { ObjectMapper mapper = new ObjectMapper(); try { Person person = mapper.readValue(new File("c:/person.json"), Person.class); System.out.println(person.getName() + ":" + person.getAge()); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 直接转化为map public static void readJsonMap() { ObjectMapper mapper = new ObjectMapper(); try { // 需要注意的是这里的Map实际为一个LikedHashMap,即链式哈希表,可以按照读入顺序遍历 Map map = mapper.readValue(new File("c:/person.json"), Map.class); System.out.println(map.get("name") + ":" + map.get("age")); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 2、jackson在实际应用中给我们提供了一系列注解,提高了开发的灵活性,下面介绍一下最常用的一些注解: @JsonIgnoreProperties:此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。@JsonIgnore:此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。@JsonFormat:此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")@JsonSerialize:此注解用于属性或者getter方法上或者类上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。@JsonDeserialize:此注解用于属性或者setter方法上或者类上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize。看一些例子: public class CustomDoubleSerialize extends JsonSerializer { private DecimalFormat df = new DecimalFormat("##.00"); @Override public void serialize(Double value, JsonGenerator jgen,SerializerProvider provider) throws IOException,JsonProcessingException { jgen.writeString(df.format(value)); } } public class CustomDateDeserialize extends JsonDeserializer { private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Date date = null; try { date = sdf.parse(jp.getText()); } catch (ParseException e) { e.printStackTrace(); } return date; } } //表示序列化时忽略的属性 @JsonIgnoreProperties(value = { "word" }) public class Person { private String name; private int age; private boolean sex; private Date birthday; private String word; private double salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isSex() { return sex; } public void setSex(boolean sex) { this.sex = sex; } public Date getBirthday() { return birthday; } // 反序列化一个固定格式的Date @JsonDeserialize(using = CustomDateDeserialize.class) public void setBirthday(Date birthday) { this.birthday = birthday; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } // 序列化指定格式的double格式 @JsonSerialize(using = CustomDoubleSerialize.class) public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public Person(String name, int age) { this.name = name; this.age = age; } public Person(String name, int age, boolean sex, Date birthday, String word, double salary) { super(); this.name = name; this.age = age; this.sex = sex; this.birthday = birthday; this.word = word; this.salary = salary; } public Person() { } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", sex=" + sex + ", birthday=" + birthday + ", word=" + word + ", salary=" + salary + "]"; } }3、使用jackson格式化时间的几种方式: 方法一:mapper.setDateFormat(format); class User { private Integer id; private String name; private Date brith; //set、get方法 } //测试 Public class Test { Public static void main(String… args) { ObjectMapper mapper = new ObjectMapper(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); mapper.setDateFormat(format); User user = new User(1,"JACK",new Date()); String outJson = mapper.writeValueAsString(user); System.out.println(outJson); } }方法二: @JsonSerialize(using = CustomDateSerializer.class) class User { private Integer id; private String name; private Date brith; //set、get方法 } class CustomDateSerializer extends JsonSerializer { @Override public void serialize(User1 value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField("id", value.getId()); jgen.writeStringField("name", value.getName()); SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd"); String tr = format.format(value.getBrith()); jgen.writeStringField("brith", tr); jgen.writeEndObject(); } } //测试 public class JackSonTest { public static void main(String[] args) throws Exception{ ObjectMapper mapper = new ObjectMapper(); User1 user = new User1(1,"JACK",new Date()); String outJson = mapper.writeValueAsString(user); System.out.println(outJson); } } 注:在类上使用了JsonSerialize注解,如果不用注解,也可以通过下面方式完成: public static void main(String[] args) throws Exception{ Usre user = new Usre(1, "theItem", new Date()); ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(Usre.class, new CustomDateSerializer()); mapper.registerModule(module); String serialized = mapper.writeValueAsString(user); }方法三:@JsonFormat注解 class User { private Integer id; private String name; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8") private Date brith; //set、get方法 } //测试 public class JackSonTest2 { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); User2 user = new User2(1,"JACK2",new Date()); String outJson = mapper.writeValueAsString(user); System.out.println(outJson); } }
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |