fastjson解析任意json

fastjson解析任意json到beanjava

解析案例的代碼
package com.base.config;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonParse {
    
    public static void main(String[] args) {
        
        String arrJson = "[{\"id\":1,\"mobile\":15809619172},{\"id\":2,\"mobile\":14588827746}]";
        List<Student> stus = JSONArray.parseArray(arrJson, Student.class);
        
        System.out.println("array json的解析結果:");
        
        for (Student stu : stus) {
            System.out.println(stu);
        }
        
        String beanJson = "{\"id\":1,\"mobile\":15809619172}";
        Student stu = JSONObject.parseObject(beanJson, Student.class);
        System.out.println("beanjson的解析結果:");
        System.out.println(stu);
        
    }

}
Student的代碼
package com.base.config;

public class Student {
    private int id;
    private String mobile;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    
    @Override
    public String toString() {
        return "Student [id=" + id + ", mobile=" + mobile + "]";
    }

}

 

程序運行結果
array json的解析結果:
Student [id=1, mobile=15809619172]
Student [id=2, mobile=14588827746]
beanjson的解析結果:
Student [id=1, mobile=15809619172]

這樣解析效率很高,並且代碼很是簡單。比json-lib庫要簡化很是多。因此強烈推薦使用fastjson.web

相關文章
相關標籤/搜索