首页 > 代码库 > JSON

JSON

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、从对象(集合)到字符串
        User u1=new User(999,"admin","123456");
        u1.setBrithday(new Date());
        String ju1=JSONObject.toJSONString(u1);
        
        System.out.println("u1="+ju1);
        //集合
        
        List<User>lu=new ArrayList<User>();
        
        lu.add(new User(111,"User1","111"));
        lu.add(new User(222,"User2","111"));
        lu.add(new User(333,"User3","111"));
        lu.add(new User(444,"User4","111"));
        lu.add(new User(555,"User5","111"));
        
        String jlu=JSONArray.toJSONString(lu);
        
        System.out.println("jlu="+jlu);
        //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>lu2=JSONArray.parseArray(jlu, User.class);
        
        for(User u:lu2)
        {
            System.out.println(u);
        }
          try {
            org.json.JSONArray ja=new org.json.JSONArray(jlu);
            
            org.json.JSONObject u3=ja.getJSONObject(0);
            
            System.out.println(u3);
            
        } catch (JSONException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        
        

    }

}

运行图:

技术分享

 

JSON