java Jackson类学习

原创
2017/05/12 10:51
阅读数 68

使用jackson的ObjectMapper 的writeValueAsString方法可以把pojo类(domain)输出成json字符串

结果显示为

{"username":"FDASBASE","driverClassName":"dm.jdbc.driver.DmDriver","password":"FDASBASE","url":"jdbc:dm://localhost:5236/FDASBASE"}

public class JacksonTester {
   public static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";

      try {
         Student student = mapper.readValue(jsonString, Student.class);  //将json字符串转换成JavaBean对象
         System.out.println(student);     // [ name: Mahesh, age: 21 ]
         mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
         jsonString = mapper.writeValueAsString(student);      //转为json格式
         System.out.println(jsonString);  //{"name" : "Mahesh","age" : 21}

      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

student  pojo类

 

 

 

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部