fastjson应该是java中对json处理性能最好的jar包了,只需要引入fastjson一个jar包即可,无需其他依赖!
下面是fastjson的一些常用的用法!
javabean 转 JSONObject: JSON.toJSON(javabean); //需要强转化
javabean的集合 转 JSONArray: JSON.toJSON(javabean的集合); //需要强转化
JSONObject 转 javabean: JSON.toJavaObject(json,Class);
JSONArray 转 javabean的集合:json.toJavaObject(jsonArray,List.class) //
package com.loger.fastjson; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class MyTest { public static void main(String[] args) throws ParseException { User user = new User("007","陈乐"); List<User> list = new ArrayList<>(); list.add(user); list.add(user); JSONObject o = new JSONObject(); o = (JSONObject) JSON.toJSON(user); System.out.println("测试javabean变JSONObject:\n"+o); System.out.println("--------------------"); User user2 = JSON.toJavaObject(o, User.class); System.out.println("测试JSONObject变javabean:\n"+user2); System.out.println("--------------------"); JSONArray jsonArray = (JSONArray) JSON.toJSON(list); System.out.println("测试javalist变jsonarray:\n"+jsonArray); System.out.println("-------------"); List<User> list2 = JSON.toJavaObject(jsonArray, List.class); System.out.println("jsonarray变javabean集合"+list2.toString()); System.out.println("----------------"); } }
运行结果:
fastjson对日期的处理:
javabean:
package com.loger.fastjson; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; public class UserWithDate { private String name; @JSONField(format="yyyy-mm-dd") private Date date; public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public UserWithDate(String name, Date date) { super(); this.name = name; this.date = date; } public UserWithDate() { super(); } @Override public String toString() { return "UserWithDate [name=" + name + ", date=" + date + "]"; } }
Main.java
package com.loger.fastjson; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class TestForDate { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); Date date = sdf.parse("1995-09-01"); UserWithDate user = new UserWithDate("陈乐",date); JSONObject o = (JSONObject) JSON.toJSON(user); System.out.println(o); System.out.println("------------------"); UserWithDate user2 = new UserWithDate(); user2 = JSON.toJavaObject(o, UserWithDate.class); System.out.println(user2); } }
结果:
时间: 2024-11-15 09:47:12