java Jackson 庫操作 json 的基本示範

來源:互聯網
上載者:User

核心庫

http://repo1.maven.org/maven2/com/fasterxml/jackson/core/

jackson-annotations-2.2.2.jar

jackson-core-2.2.2.jar

jackson-databind-2.2.2.jar

 

檔案類型支援模組

http://repo1.maven.org/maven2/com/fasterxml/jackson/dataformat/

jackson-dataformat-xml-2.2.2.jar

 

匯入庫

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonParseException;

 

  /**   * Map 轉換為 json   */  public static void MyTest01()  {    Map<String, String> hashMap = new HashMap<String, String>();    hashMap.put("name", "zhang");    hashMap.put("sex", "1");    hashMap.put("login", "Jack");    hashMap.put("password", "123abc");    try    {      ObjectMapper objectMapper = new ObjectMapper();      String userMapJson = objectMapper.writeValueAsString(hashMap);      JsonNode node = objectMapper.readTree(userMapJson);      // 輸出結果轉意,輸出正確的資訊      System.out.println(node.get("password").asText());      // 輸出不轉意,輸出結果會包含"",這是不正確的,除非作為json傳遞,如果是輸出結果值,必須如上一行的操作      System.out.println(node.get("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 = mapper.readTree(str);      JsonNode data = root.path("data");      JsonNode birth_day = data.path("birth_day");      System.out.println(birth_day.asInt());            JsonNode birth_month = data.path("birth_month");      System.out.println(birth_month.asInt());      JsonNode msg = root.path("msg");      System.out.println(msg.textValue());    }    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 = mapper.readTree(str);      // 提取 data      JsonNode data = root.path("data");      // 提取 info      JsonNode info = data.path("info");      System.out.println(info.size());      // 得到 info 的第 0 個      JsonNode item = info.get(0);      System.out.println(item.get("id"));      System.out.println(item.get("timestamp"));      // 得到 info 的第 2 個      item = info.get(2);      System.out.println(item.get("id"));      System.out.println(item.get("timestamp"));      // 遍曆 info 內的 array      if (info.isArray())      {        for (JsonNode objNode : info)        {          System.out.println(objNode);        }      }    }    catch (Exception e)    {    }  }

 

  /**   * 建立一個 json,並向該 json 新增內容   */  public static void MyTest07()  {    try    {      ObjectMapper mapper = new ObjectMapper();      ObjectNode root1 = mapper.createObjectNode();      root1.put("nodekey1", 1);      root1.put("nodekey2", 2);      System.out.println(root1.toString());    //Create the root node      ObjectNode root = mapper.createObjectNode ();      //Create a child node      ObjectNode node1 = mapper.createObjectNode ();      node1.put ("nodekey1", 1);      node1.put ("nodekey2", 2);      //Bind the child nodes      root.put ("child", node1);      //Array of nodes      ArrayNode arrayNode = mapper.createArrayNode ();      arrayNode.add (node1);      arrayNode.add (1);      //Bind array node      root.put ("arraynode", arrayNode);      System.out.println (mapper.writeValueAsString (root));    }    catch (Exception e)    {    }  }

 

參考資料

http://wiki.fasterxml.com/JacksonInFiveMinutes

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.