一、入门
Jackson中有个ObjectMapper类很是实用,用于Java对象与JSON的互换。
1.JAVA对象转JSON[JSON序列化]

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
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
  
import com.fasterxml.jackson.databind.ObjectMapper;
  
public class JacksonDemo {
  public static void main(String[] args) throws ParseException, IOException {
    User user = new User();
    user.setName("小民"); 
    user.setEmail("xiaomin@sina.com");
    user.setAge(20);
      
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
    user.setBirthday(dateformat.parse("1996-10-01"));    
      
    /**
     * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
     * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
     * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
     * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
     * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
     * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
     */
    ObjectMapper mapper = new ObjectMapper();
      
    //User类转JSON
    //输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
    String json = mapper.writeValueAsString(user);
    System.out.println(json);
      
    //Java集合转JSON
    //输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
    List<User> users = new ArrayList<User>();
    users.add(user);
    String jsonlist = mapper.writeValueAsString(users);
    System.out.println(jsonlist);
  }
}

2.JSON转Java类[JSON反序列化]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
  
public class JacksonDemo {
  public static void main(String[] args) throws ParseException, IOException {
    String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}";
      
    /**
     * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
     */
    ObjectMapper mapper = new ObjectMapper();
    User user = mapper.readValue(json, User.class);
    System.out.println(user);
  }
}

二、Jackson支持3种使用方式:
1、Data Binding:最方便使用.
(1)Full Data Binding:

1
2
3
4
5
6
7
private static final String MODEL_BINDING = "{\"name\":\"name1\",\"type\":1}";
  public void fullDataBinding() throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    Model user = mapper.readValue(MODEL_BINDING, Model.class);//readValue到一个实体类中.
    System.out.println(user.getName());
    System.out.println(user.getType());
  }

Model类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static class Model{
    private String name;
    private int type;
      
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
    public int getType() {
      return type;
    }
    public void setType(int type) {
      this.type = type;
    }
  }

(2)Raw Data Binding:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
  Concrete Java types that Jackson will use for simple data binding are:
  JSON Type    Java Type
  object     LinkedHashMap<String,Object>
  array      ArrayList<Object>
  string     String
  number(no fraction) Integer, Long or BigInteger (smallest applicable)
  number(fraction)  Double(configurable to use BigDecimal)
  true|false   Boolean
  null      null
  */
  public void rawDataBinding() throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    HashMap map = mapper.readValue(MODEL_BINDING,HashMap.class);//readValue到一个原始数据类型.
    System.out.println(map.get("name"));
    System.out.println(map.get("type"));
  }

(3)generic Data Binding:

1
2
3
4
5
6
7
8
private static final String GENERIC_BINDING = "{\"key1\":{\"name\":\"name2\",\"type\":2},\"key2\":{\"name\":\"name3\",\"type\":3}}";
  public void genericDataBinding() throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    HashMap<String,Model> modelMap = mapper.readValue(GENERIC_BINDING,new TypeReference<HashMap<String,Model>>(){});//readValue到一个范型数据中.
    Model model = modelMap.get("key2");
    System.out.println(model.getName());
    System.out.println(model.getType());
  }

2、Tree Model:最灵活。

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
private static final String TREE_MODEL_BINDING = "{\"treekey1\":\"treevalue1\",\"treekey2\":\"treevalue2\",\"children\":[{\"childkey1\":\"childkey1\"}]}";
  public void treeModelBinding() throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);
    //path与get作用相同,但是当找不到该节点的时候,返回missing node而不是Null.
    String treekey2value = rootNode.path("treekey2").getTextValue();//
    System.out.println("treekey2value:" + treekey2value);
    JsonNode childrenNode = rootNode.path("children");
    String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();
    System.out.println("childkey1Value:"+childkey1Value);
      
    //创建根节点
    ObjectNode root = mapper.createObjectNode();
    //创建子节点1
    ObjectNode node1 = mapper.createObjectNode();
    node1.put("nodekey1",1);
    node1.put("nodekey2",2);
    //绑定子节点1
    root.put("child",node1);
    //数组节点
    ArrayNode arrayNode = mapper.createArrayNode();
    arrayNode.add(node1);
    arrayNode.add(1);
    //绑定数组节点
    root.put("arraynode", arrayNode);
    //JSON读到树节点
    JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);
    //绑定JSON节点
    root.put("valuetotreenode",valueToTreeNode);
    //JSON绑定到JSON节点对象
    JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//绑定JSON到JSON节点对象.
    //绑定JSON节点
    root.put("bindJsonNode",bindJsonNode);
    System.out.println(mapper.writeValueAsString(root));
  }

3、Streaming API:最佳性能。
 
对于性能要求高的程序,推荐使用流API,否则使用其他方法
不管是创建JsonGenerator还是JsonParser,都是使用JsonFactory。

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.jingshou.jackson;
  
import java.io.File;
import java.io.IOException;
  
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
  
public class JacksonTest6 {
  
  public static void main(String[] args) throws IOException {
    JsonFactory jfactory = new JsonFactory();
       
    /*** write to file ***/
    JsonGenerator jGenerator = jfactory.createGenerator(new File(
        "c:\\user.json"), JsonEncoding.UTF8);
    jGenerator.writeStartObject(); // {
     
    jGenerator.writeStringField("name", "mkyong"); // "name" : "mkyong"
    jGenerator.writeNumberField("age", 29); // "age" : 29
     
    jGenerator.writeFieldName("messages"); // "messages" :
    jGenerator.writeStartArray(); // [
     
    jGenerator.writeString("msg 1"); // "msg 1"
    jGenerator.writeString("msg 2"); // "msg 2"
    jGenerator.writeString("msg 3"); // "msg 3"
     
    jGenerator.writeEndArray(); // ]
     
    jGenerator.writeEndObject(); // }
    jGenerator.close();
      
    /*** read from file ***/
    JsonParser jParser = jfactory.createParser(new File("c:\\user.json"));
    // loop until token equal to "}"
    while (jParser.nextToken() != JsonToken.END_OBJECT) {
     
      String fieldname = jParser.getCurrentName();
      if ("name".equals(fieldname)) {
     
       // current token is "name",
       // move to next, which is "name"'s value
       jParser.nextToken();
       System.out.println(jParser.getText()); // display mkyong
     
      }
     
      if ("age".equals(fieldname)) {
     
       // current token is "age", 
       // move to next, which is "name"'s value
       jParser.nextToken();
       System.out.println(jParser.getIntValue()); // display 29
     
      }
     
      if ("messages".equals(fieldname)) {
     
       jParser.nextToken(); // current token is "[", move next
     
       // messages is array, loop until token equal to "]"
       while (jParser.nextToken() != JsonToken.END_ARRAY) {
     
             // display msg1, msg2, msg3
         System.out.println(jParser.getText()); 
     
       }
     
      }
     
     }
     jParser.close();
  
  }
  
}

使用Jackson来实现Java对象与JSON的相互转换的教程的更多相关文章

  1. JackSon将java对象转换为JSON字符串

    JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的writeValueA ...

  2. (后端)JackSon将java对象转换为JSON字符串(转)

    转载小金金金丶园友: JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的 ...

  3. json相关类库,java对象与json相互转换

    有效选择七个关于Java的JSON开源类库 转自:http://www.open-open.com/lib/view/open1397870197828.html 翻译: (英语原文:http://w ...

  4. FastJson、Jackson、Gson进行Java对象转换Json细节处理

    前言 Java对象在转json的时候,如果对象里面有属性值为null的话,那么在json序列化的时候要不要序列出来呢?对比以下json转换方式 一.fastJson 1.fastJson在转换java ...

  5. jackson java对象和json对象的互相转换

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

  6. FastJson、Jackson、Gson进行Java对象转换Json的细节处理

    前言 Java对象在转json的时候,如果对象里面有属性值为null的话,那么在json序列化的时候要不要序列出来呢?对比以下json转换方式 一.fastJson 1.fastJson在转换java ...

  7. Java对象、Json、Xml转换工具Jackson使用

    在Java项目中將一个对象转换成一段Json格式的字符串是非常常见的,能够实现这种需求的工具包也比较多,例如Gson.JSON-lib.Jackson等等.本文主要介绍Jackson的使用,Jacks ...

  8. Java对象转JSON时如何动态的增删改查属性

    1. 前言 日常开发中少不了JSON处理,少不了需要在JSON中添加额外字段或者删除特定字段的需求.今天我们就使用Jackson类库来实现这个功能. 2. JSON字符串增加额外字段 假如我们有这样结 ...

  9. java对象与json串互转

    1:java对象与json串转换: java对象—json串: JSONObject JSONStr = JSONObject.fromObject(object); String str = JSO ...

随机推荐

  1. Mysql局域网访问授权

    如果允许用户myuser从ip为192.168.1.1的主机连接到mysql服务器,并使用password作为密码 GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'1 ...

  2. 【ListBox】ListBox的相关操作

    Winform中两个listbox的操作是平时比较常用的操作. 本次将以一个Winform实例来分享一下两个listbox的操作,包括:listbox添加项,项的上移下移等操作. 假设有两个listb ...

  3. BZOJ3509 [CodeChef] COUNTARI 【分块 + fft】

    题目链接 BZOJ3509 题解 化一下式子,就是 \[2A[j] = A[i] + A[k]\] 所以我们对一个位置两边的数构成的生成函数相乘即可 但是由于这样做是\(O(n^2logn)\)的,我 ...

  4. hdu1693 Eat the Trees 【插头dp】

    题目链接 hdu1693 题解 插头\(dp\) 特点:范围小,网格图,连通性 轮廓线:已决策点和未决策点的分界线 插头:存在于网格之间,表示着网格建的信息,此题中表示两个网格间是否连边 状态表示:当 ...

  5. 扶苏的bitset浅谈

    bitset作为C++一个非常好用的STL,在一些题目中巧妙地使用会产生非常不错的效果.今天扶苏来分享一点bitset的基础语法和应用 本文同步发布于个人其他博客,同时作为P3674题解发布. 本文感 ...

  6. 洛谷P1558 色板游戏

    题目背景 阿宝上学了,今天老师拿来了一块很长的涂色板. 题目描述 色板长度为L,L是一个正整数,所以我们可以均匀地将它划分成L块1厘米长的小方格.并从左到右标记为1, 2, ... L.现在色板上只有 ...

  7. STL源码分析-rotate

    http://note.youdao.com/noteshare?id=4ba8ff81aa96373ba11f1b82597ec73a

  8. hdu 2608 (数论)

    hdu2608  0 or 1 题意:给你一个数N(N < 2^31), 问从 1--N 所有数的因子和S(N),求 S(N)%2 的值. 链接:http://acm.hdu.edu.cn/sh ...

  9. ACE服务端编程5:ACE日志输出和跟踪

    服务器程序经常需要在命令行中显示错误消息.状态或者用来跟踪程序的执行路径,最简单的方法是使用printf. ACE提供了更强大日志设施: 1.可以在编译时启用或禁用宏: 2.可以动态的启用或禁用宏: ...

  10. 新生代Eden与两个Survivor区的解释

    文章出处:http://ifeve.com/jvm-yong-generation/ 聊聊JVM的年轻代 1.为什么会有年轻代 我们先来屡屡,为什么需要把堆分代?不分代不能完成他所做的事情么?其实不分 ...