public class FastJson {
static class Person{
private String id;
private String name;
private int age;
public Person(){
}
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
method1();
method2();
method3();
method4();
}
static void method1(){
System.out.println("javaBean转化示例开始——————————————");
Person person = new Person("1", "fastJson", 1);
System.out.println(person);
//这里将javabean转化为json字符串
String jsonString = JSON.toJSONString(person);
System.out.println(jsonString);
//这里将json字符串转化为javabean对象
person = JSON.parseObject(jsonString, Person.class);
System.out.println(person.toString());
System.out.println("javabean转化示例结束");
}
static void method2(){
System.out.println("List<javabean>转化示例开始");
Person person1 = new Person("1", "fastJson1", 1);
Person person2 = new Person("2", "fastJson2", 2);
ArrayList<Person> persons = new ArrayList<>();
persons.add(person1);
persons.add(person2);
/*转化为json字符串*/
System.out.println("转化为json字符串");
String jsonString = JSON.toJSONString(persons);
System.out.println("json字符串"+jsonString);
//json字符串转化为list<javabean>对象
List<Person> person = JSON.parseArray(jsonString, Person.class);
System.out.println("输出整个对象"+ person);
System.out.println("person1对象"+person.get(0).toString());
System.out.println("person2对象"+person.get(1).toString());
}
static void method3(){
System.out.println("List<String>转化开始");
ArrayList<String> list = new ArrayList<>();
list.add("fastjson1");
list.add("fastjson2");
list.add("fastjson3");
String jsonString = JSON.toJSONString(list);
System.out.println("输出json字符串"+jsonString);
//解析json
JSON.parseObject(jsonString,new TypeReference<List<String>>(){});
System.out.println(list.get(0)+":"+list.get(1)+":"+list.get(2));
System.out.println("List<String>转化示例结束");
}
static void method4(){
System.out.println("list<map<String,Object>>转化正式开始");
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("key1","value1");
map.put("key2","value2");
HashMap<String, Object> map2 = new HashMap<String,Object>();
map.put("key1",1);
map.put("key2",11);
ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list.add(map);
list.add(map2);
String jsonString = JSON.toJSONString(list);
System.out.println("json字符串"+jsonString);
//解析json字符串
List<Map<String, Object>> list2 = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() {
});
System.out.println("map的key1值"+list2.get(0).get("key1"));
System.out.println("map的key2值"+list2.get(0).get("key2"));
System.out.println("ma2p的key1值"+list2.get(1).get("key1"));
System.out.println("map2的key2值"+list2.get(1).get("key2"));
}
}
fastJson 详解
最新推荐文章于 2022-10-14 15:48:38 发布