JAVA编写JSON常用的三种方法
1.jsonlib
需要引入的包也多,代码也相对多一些。
2.Gson
:谷歌的
3.FastJson
:阿里巴巴的,这几个也是性能最好的一个。(推荐)jsonlib
类
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"}]
}
}
推荐使用FastJson
:
pom依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
FastJsonTest
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"}]
}
}