java Jackson 库操作 json 的基本演示

时间:2025-01-25 09:13:49

核心库下载地址

/maven2/com/fasterxml/jackson/core/

jackson-annotations-2.2.

jackson-core-2.2.

jackson-databind-2.2.

 

文件类型支持模块

/maven2/com/fasterxml/jackson/dataformat/

jackson-dataformat-xml-2.2.

 

导入库

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

 

  /**
   * Map 转换为 json
   */
  public static void MyTest01()
  {
    Map<String, String> hashMap = new HashMap<String, String>();
    ("name", "zhang");
    ("sex", "1");
    ("login", "Jack");
    ("password", "123abc");

    try
    {
      ObjectMapper objectMapper = new ObjectMapper();
      String userMapJson = (hashMap);

      JsonNode node = (userMapJson);

      // 输出结果转意,输出正确的信息
      (("password").asText());
      // 输出不转意,输出结果会包含"",这是不正确的,除非作为json传递,如果是输出结果值,必须如上一行的操作
      (("name"));
    }
    catch (IOException e)
    {
    }
  }

 

/**
   * 解析 json 格式字符串
   */
  public static void MyTest03()
  {
    try
    {
      String str = "{\"data\":{\"birth_day\":7,\"birth_month\":6},\"errcode\":0,\"msg\":\"ok\",\"ret\":0}";

      ObjectMapper mapper = new ObjectMapper();
      JsonNode root = (str);

      JsonNode data = ("data");

      JsonNode birth_day = ("birth_day");
      (birth_day.asInt());
      
      JsonNode birth_month = ("birth_month");
      (birth_month.asInt());

      JsonNode msg = ("msg");
      (());
    }
    catch (IOException e)
    {
    }
  }

 

/**
   * json 直接提取 值
   */
  public static void MyTest05()
  {
    try
    {
      // 演示字符串
      String str = "{\"data\":{\"hasnext\":0,\"info\":[{\"id\":\"288206077664983\",\"timestamp\":1371052476},{\"id\":\"186983078111768\",\"timestamp\":1370944068},{\"id\":\"297031120529307\",\"timestamp\":1370751789},{\"id\":\"273831022294863\",\"timestamp\":1369994812}],\"timestamp\":1374562897,\"totalnum\":422},\"errcode\":0,\"msg\":\"ok\",\"ret\":0,\"seqid\":5903702688915195270}";

      ObjectMapper mapper = new ObjectMapper();
      JsonNode root = (str);

      // 提取 data
      JsonNode data = ("data");
      // 提取 info
      JsonNode info = ("info");

      (());

      // 得到 info 的第 0 个
      JsonNode item = (0);
      (("id"));
      (("timestamp"));

      // 得到 info 的第 2 个
      item = (2);
      (("id"));
      (("timestamp"));

      // 遍历 info 内的 array
      if (())
      {
        for (JsonNode objNode : info)
        {
          (objNode);
        }
      }

    }
    catch (Exception e)
    {

    }
  }

 

  /**
   * 创建一个 json,并向该 json 添加内容
   */
  public static void MyTest07()
  {
    try
    {
      ObjectMapper mapper = new ObjectMapper();
      ObjectNode root1 = ();

      ("nodekey1", 1);
      ("nodekey2", 2);

      (());

    //Create the root node
      ObjectNode root =  ();
      //Create a child node
      ObjectNode node1 =  ();
       ("nodekey1", 1);
       ("nodekey2", 2);
      //Bind the child nodes
       ("child", node1);
      //Array of nodes
      ArrayNode arrayNode =  ();
       (node1);
       (1);
      //Bind array node
       ("arraynode", arrayNode);

       ( (root));
      // 得到的输出信息
      // {"child":{"nodekey1":1,"nodekey2":2},"arraynode":[{"nodekey1":1,"nodekey2":2},1]}
    }
    catch (Exception e)
    {

    }
  }

 

  // 创建一个 array node
  public static void MyTest07()
  {
    try
    {
      ObjectMapper mapper = new ObjectMapper();
      ArrayNode arrayNode = ();

      int i = 0;
      // 在 array 内创建 3 组 node 存入 array
      for (i = 0; i < 3; i++)
      {
        // 创建一个 node
        ObjectNode node = ();

        ("nodeA", i);
        ("nodeB", i);
        ("nodeC", i);

        // 向 array 内添 node
        (node);
      }

      // 根
      ObjectNode root = ();
      ("total", i);
      ("rows", arrayNode);

      ((root));
      // 得到的输出信息
      // {"total":3,"rows":[{"nodeA":0,"nodeB":0,"nodeC":0},{"nodeA":1,"nodeB":1,"nodeC":1},{"nodeA":2,"nodeB":2,"nodeC":2}]}
    }
    catch (Exception e)
    {
      ();
    }
  }

在添加 array 节点时,put node 的方法已经过时,将使用 set 方法 添加 array 节点,举例:

("rows", arrayNode);

 

将 java object 转化为 json string,被转换的对象类似 YourObject 这样,利用 ObjectWrite 进行转换。

 

public YourObject
{
  private str = "";
  public void setStr(String str)
  {
     = str;
  }
  public String getStr()
  {
    return str;
  }
}

 

    // 将 java 对象 转换为 json string
    ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = null;
    try
    {
      json = (yourObject);
    }
    catch (JsonProcessingException e)
    {
      ();
    }

 

XML 转换为 JSON 也可以利用 Jackson 完成

 

  /**
   * 将 XML 转换为 JSON
   * @param args
   */
  public void XML2JSON()
  {
    String xml = "<default><column><title>Title 1</title><id>id1</id><value>val1</value></column>"
        + "<column><title>Title 2</title><id>id2</id><value>val2</value></column>"
        + "<column><title>Title 3</title><id>id3</id><value>val3</value></column></default>";
    try
    {
      XmlMapper xmlMapper = new XmlMapper();
      Map entries = (xml, );
      ObjectMapper jsonMapper = new ObjectMapper();
      String json = (entries);
      (json);
    }
    catch (JsonParseException e)
    {
      ();
    }
    catch (JsonMappingException e)
    {
      ();
    }
    catch (JsonProcessingException e)
    {
      ();
    }
    catch (IOException e)
    {
      ();
    }
  }

 

 

 

 

 

JsonNode 字符串类型:textValue 有效, asText 有效,toString 获取的结果带引号
JsonNode 数值类型:textValue 获得的是 null, asText 有效, toString 有效,各输出方式比较如下,附代码:

 

原始信息 toString() asText() textValue() numberType()
123 123 123 null INT
123.456 123.456 123.456 null DOUBLE
"123.45600" "123.45600" 123.456 123.456 null
"" ""     null
"0" "0" 0 0 null
"null" "null" null null null
null null null null null

 

 

package other;

import ;
import ;
import ;
import ;
import ;
import ;

import ;

import ;
import ;
import ;
import ;

public class Jackson1
{

  public static void main(String[] args)
  {
    String str = "{\"data\":{\"number1\":123,\"number2\":123.45600,\"number3\":\"123.45600\""
        + ",\"number4\":\"\",\"number5\":\"0\",\"number6\":\"null\",\"number7\":null}}";

    try
    {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode root = (str);

      JsonNode data = ("data");

      for (int i = 1; i <= 7; i++)
      {
        String strNodeName = "number" + (i);

        if ((strNodeName) == true)
        {
          (("原始节点信息 %s", (strNodeName)));

          String str1 = (strNodeName).toString();
          (("toString() 输出: %s", str1));

          String str2 = (strNodeName).asText();
          (("asText() 输出: %s", str2));

          String str3 = (strNodeName).textValue();
          (("textValue() 输出: %s", str3));

          NumberType str4 = (strNodeName).numberType();
          (("numberType() 显示: %s", str4));

          ("-----------------------------------------------");
        }
      }
    }
    catch (JsonProcessingException e)
    {
      ();
    }
    catch (IOException e)
    {
      ();
    }
  }
}

参考资料
/FasterXML/jackson

​​​​​​​
Q群讨论 236201801