赞
踩
1.maven引用
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.39</version>
<scope>compile</scope>
</dependency>
2.代码实类
package com.cjm.mvnbook.test5;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cjm.mvnbook.model.Student;
public class FastJsonTest {
public static void main(String[] args) {
String a1 = BeanToJson();
JsonToBean(a1);
String a2 = ListToJSON();
JSONToList(a2);
}
//java对象转json
public static String BeanToJson(){
Student student = new Student();
student.setId(1);
student.setName("jag");
student.setSex("man");
student.setAge(25);
student.setHobby(new String[]{"篮球","上网","跑步","游戏"});
String string = JSONObject.toJSONString(student);
System.out.println(string);
return string;
}
//json转java对象
public static void JsonToBean(String s1){
Student parseObject = JSONObject.parseObject(s1, Student.class);
System.out.println(parseObject.getName());
}
//list转json
public static String ListToJSON(){
List<Student> list1 = new ArrayList<Student>();
Student student = new Student();
student.setId(1);
student.setName("jag");
student.setSex("man");
student.setAge(25);
student.setHobby(new String[]{"篮球","上网","跑步","游戏"});
list1.add(student);
Student student1 = new Student();
student1.setId(1);
student1.setName("jag");
student1.setSex("man");
student1.setAge(25);
student1.setHobby(new String[]{"篮球","上网","跑步","游戏"});
list1.add(student1);
System.out.println(JSONArray.toJSONString(list1));
System.out.println(JSONObject.toJSONString(list1));
return JSONArray.toJSONString(list1);
}
//json转list
public static void JSONToList(String s1){
List<Student> parseObject = JSONArray.parseArray(s1, Student.class);
System.out.println(parseObject.get(0).getName());
}
}

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。