Conversion between Json and bean

This article uses the json-lib jar package to realize the mutual conversion between Json and beans

 

1. Convert the string to JSON

Use the JSONObject.fromObject(str) method to convert a string to a JSON object

Use JSONObject.put("attribute","value") to add attributes to JSON

If you need to convert to a JSON array, just use the methods provided by the JSONArray object.

 

/** 
   * some simple conversions
   */   
  public  static  void transformStringTest() {  
      String str = "{" + "\"id\":" + "\"1\"," + "\"name\":" + "\"zhangsan\""  
              + "}" ;  
       // 1. Convert the string to JSON   
      JSONObject jsonObj = JSONObject.fromObject(str);  
      System.out.println(jsonObj.toString());  
      // JSON add property   
      jsonObj.put("age", "22" );  
      System.out.println(jsonObj.toString());  
      // 2. Convert the object to an array   
      JSONArray jsonArr = JSONArray.fromObject(jsonObj);  
      System.out.println(jsonArr.toString());  
      // 3. Add the array to the JSON object   
      JSONObject obj = new JSONObject();  
      obj.put("employees", jsonArr);  
      System.out.println(obj.toString());  
  }  
/* output content
 * {"id":"1","name":"zhangsan"}  
 * {"id":"1","name":"zhangsan","age":"22"}
 * [{"id":"1","name":"zhangsan","age":"22"}]
 * {"employees":[{"id":"1","name":"zhangsan","age":"22"}]}
 */  

 

 

2. Convert the object to JSON

First create the People class

 

public class People {  
    private String name;  
  
    private String idcard;  
  
    public People() {  
    }  
  
    public People(String name, String idcard) {  
        this.name = name;  
        this.idcard = idcard;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public String getIdcard() {  
        return idcard;  
    }  
  
    public void setIdcard(String idcard) {  
        this.idcard = idcard;  
    }  
  
}

 

 

Converting an object to JSON also uses the SONObject.fromObject(obj) method

If it is a List, you need to use JSONArray to convert the object to JSON array when converting to JSON

 

public  static  void transformObjectTest() {  
        People p1 = new People("a", "111111" );  
         // 1. Convert the object to json   
        System.out.println(JSONObject.fromObject(p1));  
        List<People> peopleList = new ArrayList<People>();  
        peopleList.add(p1);  
        // 2. Convert list to json (requires array JSONArray)   
        JSONArray arr = JSONArray.fromObject(peopleList);  
        System.out.println(arr.toString());  
    }   

/* output content
    * {"idcard":"111111","name":"a"}  
    * [{"idcard":"111111","name":"a"}]
    */ 

 

 

3. JSON to bean

The method of converting json to bean is also very simple, just use the JSONObject.toBean() method. When using this method, you need to pass in the class of the bean

 

/** 
     * Convert json to bean
     * @param json 
     * @param type 
     * @return 
     */  
    public static <T> Object transformJsonToBean(String json, Class<T> type) {  
        JSONObject jsonObject = JSONObject.fromObject(json);  
        return JSONObject.toBean(jsonObject, type);  
    }  

 

 

4. Convert JSON to list<bean> collection

Since it is a collection, you need to use JSONArray. JSONArray provides the toCollection method, which also requires the class of the bean to be passed in.

public static <T> Object transformJsonToBeanList(String jsonArr,  
           Class<T> type) {  
       JSONArray jsonArray = JSONArray.fromObject(jsonArr);  
       return JSONArray.toCollection(jsonArray, type);  
   }  
 
 
/**  
 * Project name: tools  
 * Project package name: com.songfayuantools.json  
 * Created: Jul 31, 2017 11:58:51 AM  
 * Creator: Administrator-Song Fayuan  
 * Create location:  
 */  
package com.songfayuantools.json;  
  
import com.songfayuantools.entity.UserInfo;  
  
import net.sf.json.JSON;  
import net.sf.json.JSONObject;  
import net.sf.json.xml.XMLSerializer;  
  
/**  
 * Description: Detailed explanation of how to use JSONObject  
 * The JSONObject-lib package is a package that converts beans, collections, maps, java arrays and xml to JSON.  
 * @author songfayuan  
 * Jul 31, 2017 11:58:51 AM  
 */  
public class Json {  
  
    /**  
     * Description: json string to java code  
     * @author songfayuan  
     * August 2, 2017 at 2:24:47 pm  
     */   
    public  static  void jsonToJava() {  
        System.out.println( "json string to java code" );  
        String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";  
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);  
        String username = jsonObject.getString("username");  
        String password = jsonObject.getString("password");  
        System.err.println("json--->java \n username="+username+"\t passwor="+password);  
    }  
      
    /**  
     * Description: The java code is encapsulated as a json string  
     * @author songfayuan  
     * August 2, 2017 at 2:30:58 pm  
     */   
    public  static  void javaToJSON() {  
        System.out.println( "java code is encapsulated as json string" );  
        JSONObject jsonObject = new JSONObject();  
        jsonObject.put("username", "宋发元");  
        jsonObject.put("age", 24);  
        jsonObject.put("sex", "男");  
        System.out.println("java--->json \n " + jsonObject.toString());  
    }  
      
    /**  
     * Description: json string to xml string  
     * @author songfayuan  
     * August 2, 2017 at 2:56:30 pm  
     */   
    public  static  void jsonToXML() {  
        System.out.println( "json string to xml string" );  
        String jsonStr = "{\"username\":\"宋发元\",\"password\":\"123456\",\"age\":\"24\"}";  
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);  
        XMLSerializer xmlSerializer = new XMLSerializer();  
        xmlSerializer.setRootName("user_info");  
        xmlSerializer.setTypeHintsEnabled(false);  
        String xml = xmlSerializer.write(jsonObject);  
        System.out.println("json--->xml \n" + xml);  
    }  
      
    /**  
     * Description: xml string to json string  
     * @author songfayuan  
     * August 2, 2017 at 3:19:25 pm  
     */   
    public  static  void xmlToJSON() {  
        System.out.println( "xml string to json string" );  
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>宋发元</username></user_info>";  
        XMLSerializer xmlSerializer = new XMLSerializer();  
        JSON json = xmlSerializer.read(xml);  
        System.out.println("xml--->json \n" + json.toString());  
    }  
      
    /**  
     * Description: javaBean to json string  
     * @author songfayuan  
     * August 2, 2017 at 3:39:10 pm  
     */  
    public static void javaBeanToJSON() {  
        System.out.println( "javaBean to json string" );  
        UserInfo userInfo = new UserInfo();  
        userInfo.setUsername("宋发元");  
        userInfo.setPassword("123456");  
        JSONObject jsonObject = JSONObject.fromObject(userInfo);  
        System.out.println("JavaBean-->json \n" + jsonObject.toString());  
    }  
      
    /**  
     * Description: javaBean to xml string  
     * @author songfayuan  
     * August 2, 2017 at 3:48:08 pm  
     */  
    public static void javaBeanToXML() {  
        System.out.println( "javaBean to xml string" );  
        UserInfo userInfo = new UserInfo();  
        userInfo.setUsername("songfayuan");  
        userInfo.setPassword("66666");  
        JSONObject jsonObject = JSONObject.fromObject(userInfo);  
        XMLSerializer xmlSerializer = new XMLSerializer();  
        String xml = xmlSerializer.write(jsonObject, "UTF-8");  
        System.out.println("javaBean--->xml \n" + xml);  
    }  
      
    public static void main(String args[]) {  
//      jsonToJava();  
//      javaToJSON();  
//      jsonToXML();  
//      xmlToJSON();  
//      javaBeanToJSON();  
        javaBeanToXML();  
    }  
      
}  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325852109&siteId=291194637