Java FastJson频繁使用
- public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
- *public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
- *public static final T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean
- *public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
- *public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
- *public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
- public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
- public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。
package demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map.Entry;
import com.alibaba.fastjson.JSON;
public class P {
static class Student {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public Student(long id, String name) {
this.id = id;
this.name = name;
}
public Student() {
}
}
@SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
Student s1 = new Student(0, "name");
Student s2 = new Student(2, "name2");
//转为json数组 [{"id":0,"name":"name"},{"id":2,"name":"name2"}]
ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
//将集合或者对象序例化成JSON 序号json {"0":{"name":"name","id":0},"1":{"name":"name2","id":2}}
HashMap<Integer, Student> map = new HashMap<>();
map.put(0, s1);
map.put(1, s2);
//处理json数组 {"studentlist":[{"name":"name","id":0},{"name":"name2","id":2}]}
Hashtable<String, ArrayList<Student>> hashtable = new Hashtable<>();
hashtable.put("studentlist", list);
System.out.println(JSON.toJSONString(list));
System.out.println(JSON.toJSON(map));
System.out.println(JSON.toJSON(hashtable));
// 转换对象 处理map 转对象
for (Entry<Integer, Student> entry : map.entrySet()) {
Student value = entry.getValue();
System.out.println(value.getName());
System.out.println(value.getId());
}
//Json串反序列化成对象
JSON json = (JSON) JSON.toJSON(s1);
//注意[ ] 号
List<Student> parseArray = JSON.parseArray("[{\"id\":0,\"name\":\"name\"},{\"id\":2,\"name\":\"name2\"}]", Student.class);
//
for (Student student : parseArray) {
System.out.println(student.getId());
System.out.println(student.getName());
}
}
}