json和對象相互轉化方法


1.maven配置

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>

2.demo代碼 

/**
 * 
 */
package jsontest;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;

/**
 * @author jhuang.sjtu
 * @function null都會過濾掉
 * @date 2017年12月10日
 * @version
 */
public class TestJson {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //對象轉化為json
        User use = new User("admin", null, 20);
        String ss = new Gson().toJson(use);
        System.out.println(ss);
        
        //json轉化為對象
        User use222 = new Gson().fromJson(ss, User.class);
        System.out.println("use222"+use222.toString());
        
        System.out.println("以上為方法1,以下為方法2===================");
        
        // 用戶組對象轉JSON串  
        String jsonString = JSON.toJSONString(use);  
        System.out.println("jsonString:" + jsonString);  
        // JSON串轉用戶組對象  
        User group2 = JSON.parseObject(jsonString, User.class);  
        System.out.println("group2:" + group2);  
        
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM