首页 > 代码库 > FASTJSON

FASTJSON

package com.hanqi.test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;

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

public class testJSON {

public static void main(String[] args) {
    //测试JSON解析
    
    //1从对象(集合)到JSON字符串
    
    User u1=new User(999,"admin","123456");
    u1.setBirthday(new Date());
    String ju1=JSONObject.toJSONString(u1);
    System.out.println("ju1="+ju1);
    
    //2从JSON字符串到对象(集合)

    User u2=JSONObject.parseObject(ju1,User.class);
    
    System.out.println("u2="+u2);
    
    try {
        org.json.JSONObject jo=new org.json.JSONObject(ju1);
        
        int userid=jo.getInt("userID");
        
        System.out.println("userID="+userid);
        
    
        
        
    } catch (JSONException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
    }
    //集合
    List<User> lu=new ArrayList<>();
    lu.add(new User(111,"user1","111"));
    lu.add(new User(211,"user2","111"));
    lu.add(new User(311,"user3","111"));
    lu.add(new User(411,"user4","111"));
    lu.add(new User(511,"user5","111"));
    String jlu=JSONArray.toJSONString(lu);
    System.out.println("jlu="+jlu);
    List<User> l=JSONArray.parseArray(jlu, User.class);
    for(User u: l)
    {
        System.out.println(u);
    }
    
    

//
// try {
// org.json.JSONArray ja=new org.json.JSONArray();
// org.json.JSONObject u3=ja.getJSONObject(0);
// System.out.println("u3="+u3);
// } catch (JSONException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }
//

}

}

FASTJSON