Home Java javaTutorial Tutorial on using Jackson to convert Java objects to JSON and vice versa

Tutorial on using Jackson to convert Java objects to JSON and vice versa

Feb 16, 2017 pm 04:54 PM
jackson

一、入门

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

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); 
  } 
}
Copy after login

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

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); 
  } 
}
Copy after login

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

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()); 
  }
Copy after login

Model类:

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; 
    } 
  }
Copy after login

(2)Raw Data Binding:

/** 
  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")); 
  }
Copy after login

 (3)generic Data Binding:

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()); 
  }
Copy after login

2、Tree Model:最灵活。

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)); 
  }
Copy after login

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

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(); 
 
  } 
 
}
Copy after login

更多使用Jackson来实现Java对象与JSON的相互转换的教程相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Convert CSV to JSON using Jackson library in Java? Convert CSV to JSON using Jackson library in Java? Aug 18, 2023 pm 11:49 PM

AJackson is a Java JSON API that provides several different ways to process JSON. We can convert CSV data to JSON data using the CsvMapper class, which is a special ObjectMapper with extended functionality to convert POJOs into CsvSchema instances. We can build an ObjectReader with default settings using the reader() method. In order to convert we need to import com.fasterxml.jac

How to solve the problem of specifying jackson version in SpringBoot upgrade How to solve the problem of specifying jackson version in SpringBoot upgrade May 12, 2023 pm 02:13 PM

[Vulnerability Notice] On February 19, NVD issued a security notice disclosing a remote code execution vulnerability (CVE-2020-8840) in jackson-databind caused by JNDI injection, with a CVSS score of 9.8. The affected version of jackson-databind lacks certain xbean-reflect/JNDI blacklist classes, such as org.apache.xbean.propertyeditor.JndiConverter, which can lead to attackers using JNDI injection to achieve remote code execution. At present, the manufacturer has released a new version to complete the vulnerability repair. Relevant users are requested to upgrade in time for protection. Since the S used in the project

Convert XML to POJO using Jackson library in Java? Convert XML to POJO using Jackson library in Java? Aug 30, 2023 am 10:21 AM

TheJSONJacksonisalibraryforJava.IthasverypowerfuldatabindingcapabilitiesandprovidesaframeworktoserializecustomjavaobjectstoJSONanddeserializeJSONbacktoJavaobject.WecanalsoconvertanXMLformattothePOJOobjectusingthereadValue()methodoftheXmlMapper&nb

Convert POJO to XML using Jackson library in Java? Convert POJO to XML using Jackson library in Java? Sep 18, 2023 pm 02:21 PM

Jackson is a Java-based library that is useful for converting Java objects to JSON and JSON to Java objects. JacksonAPI is faster than other APIs, requires less memory area, and is suitable for large objects. We use the writeValueAsString() method of the XmlMapper class to convert the POJO to XML format, and the corresponding POJO instance needs to be passed as a parameter to this method. Syntax publicStringwriteValueAsString(Objectvalue)throwsJsonProcessingExceptionExampleimp

How to convert JSON object to enum type in Java using Jackson? How to convert JSON object to enum type in Java using Jackson? Sep 05, 2023 pm 12:13 PM

JSONObject can parse text in a string to generate a Map type object. Enumerations can be used to define collections of constants, and we can use enumerations when we need a predefined list of values ​​that does not represent some kind of numeric or textual data. We can convert JSON objects into enumerations using the readValue() method of the ObjectMapper class. In the example below, we can use the Jackson library to convert/deserialize a JSON object into a Java enumeration. Example importcom.fasterxml.jackson.databind.*;publicclassJSONToEnumTest{&

How to get JSONParser's default settings using Jackson in Java? How to get JSONParser's default settings using Jackson in Java? Sep 12, 2023 am 11:57 AM

The default settings for all JSON parsers can be represented using the JsonParser.Feature enumeration. JsonParser.Feature.values() will return all features available for JSONParser, but whether a feature is enabled or disabled for a specific parser can be determined using JsonParser's isEnabled() method. Syntax publicstaticenumJsonParser.FeatureextendsEnum<JsonParser.Feature>Example importcom.fas

How to use Jackson serialization to achieve data desensitization in Java How to use Jackson serialization to achieve data desensitization in Java Apr 18, 2023 am 09:46 AM

1. Background: Some sensitive information in the project cannot be displayed directly, such as customer mobile phone numbers, ID cards, license plate numbers and other information. Data desensitization is required when displaying to prevent the leakage of customer privacy. Desensitization means treating part of the data with desensitization symbols (*). 2. When the target returns data from the server, use Jackson serialization to complete data desensitization to achieve desensitized display of sensitive information. Reduce the amount of repeated development and improve development efficiency to form unified and effective desensitization rules. It can be based on the desensitize method of rewriting the default desensitization implementation to realize the desensitization requirements of scalable and customizable personalized business scenarios. 3. Main implementation 3.1 Based on Jackson Custom desensitized serialization implementation of StdSerializer: all standard

When to use @ConstructorProperties annotation when using Jackson in Java? When to use @ConstructorProperties annotation when using Jackson in Java? Aug 27, 2023 pm 08:53 PM

The @ConstructorProperties annotation comes from the java.bean package and is used to deserialize JSON into java objects through an annotated constructor. This annotation is supported starting from Jackson 2.7. The way this annotation works is very simple, instead of annotating each parameter in the constructor, we can provide an array containing the property names for each constructor parameter. Syntax@Documented@Target(value=CONSTRUCTOR)@Retention(value=RUNTIME)public@interfaceConstructorPropertiesExample impo

See all articles