今天给大家讲一个对象,对象集合转json数据的三种方法,三种方法最终达到的效果是一样的。
1,jsonlib:个人感觉最麻烦的一个需要引入的包也多,代码也相对多一些。
2,Gson:谷歌的
3,FastJson:阿里巴巴的,个人觉得这个比较好,而且据说这个也是性能最好的一个。
关于demo里面所使用的罐包,可以自行去下载,也可以加我QQ我给你:1140459171
Jsonlib:package json;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import user.User;
public class Jsonlib {
public static void main(String[] args) {
User user1 = new User();
user1.setUsername("111");
user1.setPassword("111");
User user2 = new User();
user2.setUsername("222");
user2.setPassword("222");
List<User> lists = new ArrayList<User>();
lists.add(user1);
lists.add(user2);
JSONArray fromObject1 = JSONArray.fromObject(user1);
JSONArray fromObject2 = JSONArray.fromObject(lists);
String str1 = fromObject1.toString();
String str2 = fromObject2.toString();
System.out.println(str1);
//打印结果
//[{"password":"111","username":"111"}]
System.out.println(str2);
//打印结果
//[{"password":"111","username":"111"},{"password":"222","username":"222"}]
}
}
jar:
Gson:
package json;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import user.User;
public class Gson_a {
public static void main(String[] args) {
User user1 = new User();
user1.setUsername("111");
user1.setPassword("111");
User user2 = new User();
user2.setUsername("222");
user2.setPassword("222");
List<User> lists = new ArrayList<User>();
lists.add(user1);
lists.add(user2);
Gson gson = new Gson();
String json1 = gson.toJson(user1);
System.out.println(json1);
//打印结果
//{"username":"111","password":"111"}
String json2 = gson.toJson(lists);
System.out.println(json2);
//打印结果
//[{"username":"111","password":"111"},{"username":"222","password":"222"}]
}
}
jar:
FastJson:
package json;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import user.User;
public class FastJson {
public static void main(String[] args) {
User user1 = new User();
user1.setUsername("111");
user1.setPassword("111");
//1、单个对象转换成json
String jsonString = JSON.toJSONString(user1);
System.out.println(jsonString);
//打印结果
//{"password":"111","username":"111"}
User user2 = new User();
user2.setUsername("222");
user2.setPassword("222");
List<User> lists = new ArrayList<User>();
lists.add(user1);
lists.add(user2);
String jsonString2 = JSON.toJSONString(lists);
System.out.println(jsonString2);
//打印结果
//[{"password":"111","username":"111"},{"password":"222","username":"222"}]
}
}