Illustrate the use of the ObjectMapper class in Java's Jackson library

  • 2020-04-01 04:35:53
  • OfStack

The ObjectMapper class is the main class of the Jackson library. It provides some functionality to convert Java objects to match JSON structures and vice versa. It USES instances of JsonParser and JsonGenerator to actually read/write JSON.

Class declaration
The following is a org. Codehaus. Jackson. The map. ObjectMapper class declaration:


public class ObjectMapper
  extends ObjectCodec
   implements Versioned

Nested classes

S.N. class & describe
1 static class ObjectMapper.DefaultTypeResolverBuilder// custom TypeResolverBuilder To provide so-called "default input" using the type resolution builder (see enableDefaultTyping() For details).
2 static class ObjectMapper.DefaultTyping// use enableDefaultTyping() Enumeration specifies what type (class) default input should be used.

The constructor
S.N. The constructor & describe
1 ObjectMapper()// The default constructor, which builds the default JsonFactory Use when necessary StdSerializerProvider As its SerializerProvider And, BeanSerializerFactory As its SerializerFactory .
2 ObjectMapper(JsonFactory jf)// Constructs use the specified JsonFactory Build necessary JsonParsers and / or JsonGenerators Mapping.
3 ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp)
4 ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp, SerializationConfig sconfig, DeserializationConfig dconfig)
5 ObjectMapper(SerializerFactory sf) Not recommended. Use other constructs instead ; Note that you can set up a serialization factory setSerializerFactory ( org.codehaus.jackson.map.SerializerFactory )

This class inherits the following class methods:
java.lang.object

example
The basic code for the test class is as follows


 
 
public class Jackson { 
   
  public static JsonGenerator jsonGenerator = null; 
  private static ObjectMapper mapper = new ObjectMapper(); 
  public static void main(String[] args) { 
    Student student = new Student(); 
    student.setIsstudent(true); 
    student.setUid(1000); 
    student.setUname("xiao liao"); 
    student.setUpwd("123"); 
    student.setNumber(12); 
     
    Map<String, Student> stuMap = new HashMap<String, Student>(); 
    stuMap.put("1", student); 
    stuMap.put("2", student); 
     
    List<Object> stuList = new ArrayList<Object>(); 
    List<Student> stuList1 = new ArrayList<Student>(); 
    stuList1.add(student); 
    student= new Student(); 
    student.setIsstudent(false); 
    student.setUid(200); 
    student.setUname("xiao mi"); 
    stuList1.add(student); 
     
    stuList.add(student); 
    stuList.add("xiao xin"); 
    stuList.add("xiao er"); 
    stuList.add(stuMap); 
     
    //readJson2List(); 
    try { 
      //readJson2Array(); 
      //writeArray2Json(array); 
      //writeJson2List(); 
      //writeEntity2Json(student); 
      writeJson2Entity(); 
      //writeMap2Json(stuMap); 
      //writeList2Json(stuList1); 
       
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
   /** 
   * 
   * <code>writeEntity2Json</code> 
   * @description: TODO( Entity class to json) 
   * @param object 
   * @throws IOException 
   */ 
   public static void writeEntity2Json(Object object) throws IOException { 
      mapper.writeValue( new File("D:\developSoft\aaadowload\testjson1\lib\aa.txt"),object ); 
      mapper.writeValue( System.out,object ); 
      
   } 
   /** 
   * 
   * <code>writeArray2Json</code> 
   * @description: TODO( Array to json An array of ) 
   * @param object 
   * @throws IOException 
   */ 
   public static void writeArray2Json(Object object) throws IOException { 
      
     //WriteValue has the same functionality as writeObject
     mapper.writeValue( new File("D:\developSoft\aaadowload\testjson1\lib\aa.txt"),object ); 
     mapper.writeValue(System.out,object ); 
      
   } 
   /** 
   * 
   * <code>writeMap2Json</code> 
   * @description: TODO(map Object conversion to json object ) 
   * @param object 
   * @throws IOException 
   * @since  2011-11-8    Liao Yiping  
   */ 
   public static void writeMap2Json(Object object) throws IOException { 
      
     System.out.println(" use ObjectMapper-----------"); 
     //WriteValue has the same functionality as writeObject
     System.out.println("==>"+mapper.writeValueAsString(object)); 
     mapper.writeValue( new File("D:\developSoft\aaadowload\testjson1\lib\aamap.txt"),object ); 
     mapper.writeValue( System.out , object ); 
   } 
   /** 
   * 
   * <code>writeList2Json</code> 
   * @description: TODO(list Converted to json) 
   * @param object 
   * @throws IOException 
   */ 
   public static void writeList2Json(Object object) throws IOException { 
     System.out.println("==>"+mapper.writeValueAsString(object)); 
     mapper.writeValue( new File("D:\developSoft\aaadowload\testjson1\lib\aamap.txt"),object ); 
     mapper.writeValue( System.out , object ); 
   } 
   /** 
   * 
   * <code>writeJson2Entity</code> 
   * @description: TODO(json Convert to entity ) 
   * @throws IOException 
   */ 
   public static void writeJson2Entity() throws IOException { 
     System.out.println("json String into a entity-------------"); 
//    File file = new File("D:\developSoft\aaadowload\testjson1\lib\aa.txt"); 
//    FileInputStream inputStream = new FileInputStream(file); 
//    Student student = mapper.readValue(inputStream,Student.class); 
//    System.out.println(student.toString()); 
     //Beautiful output
     //mapper.defaultPrettyPrintingWriter().writeValueAsString(value); 
   
     String json = "{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}"; 
     Student student1 = mapper.readValue(json,Student.class); 
     System.out.println("json2:"+student1.toString()); 
   } 
   /** 
   * 
   * <code>writeJson2List</code> 
   * @description: TODO(json Made a special trip list object ) 
   * @throws IOException 
   */ 
   public static void writeJson2List() throws IOException { 
     System.out.println("json String into a entity-------------"); 
     File file = new File("D:\developSoft\aaadowload\testjson1\lib\aa.txt"); 
     FileInputStream inputStream = new FileInputStream(file); 
     Student student = mapper.readValue(inputStream,Student.class); 
     System.out.println(student.toString()); 
      
     String json = "[{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},{"uid":200,"uname":"xiao mi","upwd":null,"number":0.0,"isstudent":false}]"; 
     List<LinkedHashMap<String, Object>> s= mapper.readValue(json,List.class); 
     for (int i = 0; i < s.size(); i++) { 
       LinkedHashMap<String, Object> link = s.get(i); 
       Set<String> key = link.keySet(); 
       for (Iterator iterator = key.iterator(); iterator.hasNext();) { 
        String string = (String) iterator.next(); 
        System.out.println(string+"==>"+link.get(string)); 
         
      } 
       System.out.println("json:"+i+""+s.get(i).toString()); 
       
    } 
   } 
    
   public static void readJson2List() { 
    String json = "[{"uid":1,"uname":"www","number":234,"upwd":"456"}," 
     + "{"uid":5,"uname":"tom","number":3.44,"upwd":"123"}]"; 
    try { 
    List<LinkedHashMap<String, Object>> list = mapper.readValue( 
     json, List.class); 
    System.out.println(list.size()); 
    for (int i = 0; i < list.size(); i++) { 
     Map<String, Object> map = list.get(i); 
     Set<String> set = map.keySet(); 
     for (Iterator<String> it = set.iterator(); it.hasNext();) { 
     String key = it.next(); 
     System.out.println(key + ":" + map.get(key)); 
     } 
    } 
    } catch (JsonParseException e) { 
    e.printStackTrace(); 
    } catch (JsonMappingException e) { 
    e.printStackTrace(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
   } 
    
   public static void readJson2Array() { 
     String json = "[{"uid":1,"uname":"www","number":234,"upwd":"456"}," 
       + "{"uid":5,"uname":"tom","number":3.44,"upwd":"123"}]"; 
     try { 
       Student[] students = mapper.readValue(json, Student[].class); 
       for (Student student : students) { 
        System.out.println(">"+student.toString()); 
      } 
     } catch (JsonParseException e) { 
       e.printStackTrace(); 
     } catch (JsonMappingException e) { 
       e.printStackTrace(); 
     } catch (IOException e) { 
       e.printStackTrace(); 
     } 
   } 
 
} 

Print result:


 String into a entity-------------
json2:uid=1000,name=xiao liao,upwd=123,number=12.0,isStudent=true

writeMap2Json -----------
{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}

readJson2Array------------------
>uid=1,name=www,upwd=456,number=234.0,isStudent=false
>uid=5,name=tom,upwd=123,number=3.44,isStudent=false
writeMap2Json -----------
{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}

Try each one for yourself   , which is also my test code


Related articles: