Jackson以优异的解析性能赢得了好评,今天就看看Jackson的一些简单的用法。

Jackson使用之前先要下载,这里一共有三个jar包,想要获得完美的Jackson体验,这三个jar包都不可或缺。

Java–>json

1.将一个类以json字符串的形式输出:

    //将一个类以json字符串的形式输出
@Test
public void test1(){
ObjectMapper mapper = new ObjectMapper();
User user = new User();
user.setMoney(1000);
user.setUsername("张三");
user.setPassword("123");
try {
System.out.println(mapper.writeValueAsString(user));
} catch (IOException e) {
e.printStackTrace();
}
}

User.java

import java.io.Serializable;

public class User implements Serializable{

    private String username;
private String password; //添加了transient属性的字段不会被存储
private int money; public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public User() {
}
public User(String username, String password, int money) {
this.username = username;
this.password = password;
this.money = money;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

输出:

2.以json字符串的形式输出一个稍微复杂的类:

Book.java

public class Book {

    private int id;
private String name;
private int price;
private String author;
private Detail detail;
private Attribute attribute; public Attribute getAttribute() {
return attribute;
}
public void setAttribute(Attribute attribute) {
this.attribute = attribute;
}
public Detail getDetail() {
return detail;
}
public void setDetail(Detail detail) {
this.detail = detail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}

Detail.java

public class Detail {

    private String pressTime;
private String storyTime;
public String getPressTime() {
return pressTime;
}
public void setPressTime(String pressTime) {
this.pressTime = pressTime;
}
public String getStoryTime() {
return storyTime;
}
public void setStoryTime(String storyTime) {
this.storyTime = storyTime;
}
}

Attribute.java

public class Attribute {

    private String category;
private String edition;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
} }

输出为:

{"id":1,"name":"三国演义","price":20,"author":"罗贯中","detail":{"pressTime":"2001-01-01","storyTime":"196-05-06"},"attribute":{"category":"小说","edition":"9"}}

3.以json字符串输出一个List集合:

    @Test
public void test2(){
ObjectMapper mapper = new ObjectMapper();
List<User> list = new ArrayList<User>();
User u = new User("张三", "123", 1000);
list.add(u);
u = new User("李四", "456", 2000);
list.add(u);
u = new User("王五", "789", 3000);
list.add(u);
u = new User("赵六", "555", 4000);
list.add(u);
try {
System.out.println(mapper.writeValueAsString(list));
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

输出结果:

[{"username":"张三","password":"123","money":1000},{"username":"李四","password":"456","money":2000},{"username":"王五","password":"789","money":3000},{"username":"赵六","password":"555","money":4000}]

4.将一个Map以json字符串的形式输出:

    @Test
public void test3(){
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = new HashMap<String, String>();
map.put("username", "张三");
map.put("password", "123456");
try {
System.out.println(mapper.writeValueAsString(map));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}

结果为:

5.如果想把List集合中的map以json字符串格式输出,又该如何?和前文List一样。

    @Test
public void test4(){
ObjectMapper mapper = new ObjectMapper();
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
Map<String, String> map = new HashMap<String, String>();
map.put("username", "张三");
map.put("password", "123456");
list.add(map);
map = new HashMap<String, String>();
map.put("username", "李四");
map.put("password", "888888");
list.add(map);
try {
System.out.println(mapper.writeValueAsString(list));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}

6.在看看一个Map中有Book.java,Book.java中又有其他类:

    @Test
public void test1(){
ObjectMapper mapper = new ObjectMapper();
Detail detail = new Detail();
detail.setPressTime("2001-01-01");
detail.setStoryTime("196-05-06");
Attribute attr = new Attribute();
attr.setCategory("小说");
attr.setEdition("9");
Book book = new Book();
book.setAttribute(attr);
book.setAuthor("罗贯中");
book.setDetail(detail);
book.setId(1);
book.setName("三国演义");
book.setPrice(20);
Map<String, Object> map = new HashMap<String, Object>();
map.put("namespace", "books");
map.put("book", book);
try {
System.out.println(mapper.writeValueAsString(map));
} catch (IOException e) {
e.printStackTrace();
}
}

输出结果:

{"book":{"id":1,"name":"三国演义","price":20,"author":"罗贯中","detail":{"pressTime":"2001-01-01","storyTime":"196-05-06"},"attribute":{"category":"小说","edition":"9"}},"namespace":"books"}

Json–>java

1.json字符串转为javaBean:

javaBean hljs tex">    @Test
public void test5(){
String str = "{\"id\":1,\"name\":\"三国演义\",\"price\":20,\"author\":\"罗贯中\",\"detail\":{\"pressTime\":\"2001-01-01\",\"storyTime\":\"196-05-06\"},\"attribute\":{\"category\":\"小说\",\"edition\":\"9\"}}";
ObjectMapper mapper = new ObjectMapper();
try {
Book book = mapper.readValue(str, Book.class);
System.out.println(book.getAuthor()+","+book.getAttribute().getCategory());
} catch (IOException e) {
e.printStackTrace();
}
}

2.json字符串转为List

    //json-->List
@Test
public void test6(){
String str = "[{\"username\":\"张三\",\"password\":\"123\",\"money\":1000},{\"username\":\"李四\",\"password\":\"456\",\"money\":2000},{\"username\":\"王五\",\"password\":\"789\",\"money\":3000},{\"username\":\"赵六\",\"password\":\"555\",\"money\":4000}]";
ObjectMapper mapper = new ObjectMapper();
try {
List<User> us = mapper.readValue(str, new TypeReference<ArrayList<User>>() {});
for (User user : us) {
System.out.println(user.getUsername()+","+user.getMoney());
}
} catch (IOException e) {
e.printStackTrace();
}
}

3.json字符串转为Map:

    //json-->map
@Test
public void test7(){
String str = "{\"password\":\"888888\",\"username\":\"李四\"}";
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, String> map = mapper.readValue(str, new TypeReference<Map<String, String>>() {});
for (String key : map.keySet()) {
System.out.println(key+","+map.get(key));
}
} catch (IOException e) {
e.printStackTrace();
}
}

唉,仔细一琢磨,这个Jackson真的好简单,以前一直以为好难,想起来小学的课文《小马过河》,看来还是要多实践。

jackson 学习笔记的更多相关文章

  1. JackSon学习笔记(一)

    概述 Jackson框架是基于Java平台的一套数据处理工具,被称为“最好的Java Json解析器”. Jackson框架包含了3个核心库:streaming,databind,annotation ...

  2. Jackson学习笔记(详细)

    学习地址:http://tutorials.jenkov.com/java-json/index.html github地址:https://github.com/FasterXML/jackson ...

  3. Jackson学习笔记-对象序列化

    一.用ObjectMapper.readValue(jsonString, Student.class) , ObjectMapper.writeValueAsString(student) impo ...

  4. Jackson学习笔记(三)<转>

    概述 使用jackson annotations简化和增强的json解析与生成. Jackson-2.x通用annotations列表:https://github.com/FasterXML/jac ...

  5. Jackson学习笔记

    老版本的Jackson使用的包名为org.codehaus.jackson,而新版本使用的是com.fasterxml.jackson. Jackson主要包含了3个模块: jackson-core ...

  6. spring学习笔记---Jackson的使用和定制

      前言: JAVA总是把实体对象(数据库/Nosql等)转换为POJO对象再处理, 虽然有各类框架予以强力支持. 但实体对象和POJO, 由于"饮食习惯", "民族特色 ...

  7. springmvc学习笔记--REST API的异常处理

    前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...

  8. springmvc学习笔记---面向移动端支持REST API

    前言: springmvc对注解的支持非常灵活和飘逸, 也得web编程少了以往很大一坨配置项. 另一方面移动互联网的到来, 使得REST API变得流行, 甚至成为主流. 因此我们来关注下spring ...

  9. <老友记>学习笔记

    这是六个人的故事,从不服输而又有强烈控制欲的monica,未经世事的千金大小姐rachel,正直又专情的ross,幽默风趣的chandle,古怪迷人的phoebe,花心天真的joey——六个好友之间的 ...

随机推荐

  1. js node

    http://blogs.msdn.com/b/scott_hanselman/archive/2011/11/29/window-iis-node-js.aspx http://www.16kan. ...

  2. SpringSecurity的简单应用(一)

    java项目首先要提的就是jar包了,Springsecurity的jar下载地址:http://static.springsource.org/spring-security/site/downlo ...

  3. iOS开发控制器之间传值的几种小方法

    在IOS开发中或面试中,经常会遇到,两个或者多个控制器之间传值的问题 ,总结的集中方法仅供参考! 问题 :将B控制器中的textField 输入内容,传到A控制器中的label上显示出来,如何传值? ...

  4. CycleScrollView实现轮播图

    // //  CycleScrollView.h //  PagedScrollView // //  Created by 李洪强 on 16-1-23. //  Copyright (c) 201 ...

  5. Linux下实现定时器Timer的几种方法

    http://blog.csdn.net/lxmky/article/details/7669296 第六章 IO复用:select和poll函数 http://www.cnblogs.com/4ti ...

  6. OA学习笔记-009-岗位管理的CRUD

    一.分析 Action->Service->Dao CRUD有功能已经抽取到BaseDaoImpl中实现,所以RoleDaoImpl没有CRUD的代码,直接从BaseDaoImpl中继承 ...

  7. 【Xamarin挖墙脚系列:应用的性能调优】

    原文:[Xamarin挖墙脚系列:应用的性能调优] 官方提供的工具:网盘地址:http://pan.baidu.com/s/1pKgrsrp 官方下载地址:https://download.xamar ...

  8. Windows下Redis中RedisQFork位置调整

    redis-server.exe redis.windows.conf 使用上面命令启动redis服务的时候报了以下错误信息: The Windows version of Redis allocat ...

  9. 从C#到Python —— 4 类及面向对象

    http://www.cnblogs.com/yanxy/archive/2010/04/04/c2p_4.html 如果你熟悉C#,那么对类(Class)和面向对象(Object Oriented) ...

  10. [FJSC2014]圈地

    [题目描述] 2维平面上有n个木桩,黄学长有一次圈地的机会并得到圈到的土地,为了体现他的高风亮节,他要使他圈到的土地面积尽量小.圈地需要圈一个至少3个点的多边形,多边形的顶点就是一个木桩,圈得的土地就 ...