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());//long型数值 String ju1 = JSONObject.toJSONString(u1); System.out.println("ju1="+ju1); //集合 List<User> lu = new ArrayList<User>(); lu.add(new User(111,"User1","1111")); lu.add(new User(222,"User2","2222")); lu.add(new User(333,"User3","3333")); lu.add(new User(444,"User4","4444")); String jlu = JSONArray.toJSONString(lu); System.out.println("jlu="+jlu); //官方 try { org.json.JSONArray ja = new org.json.JSONArray(jlu); org.json.JSONObject u3 = ja.getJSONObject(0); System.out.println("u3="+u3.getInt("userID")); } catch (JSONException e1) { // TODO 自动生成的 catch 块 e1.printStackTrace(); } //2.从JSON字符串到对象或集合 System.out.println("2.从JSON字符串到对象或集合................."); User u2 = (User)JSONObject.parseObject(ju1, User.class); System.out.println("u2="+u2); //字符创到 集合 List<User> lu2 = JSONArray.parseArray(jlu, User.class); for(User u : lu2) { System.out.println(u); } //官方 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(); } } }