fastjson maven
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
1、Java对象–>JSON对象
public class JSONTest{
public static void main(String[] args) {
User user = new User("张三", "男", 18);
//Java对象转化为JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
System.out.println("Java对象转化为JSON对象\n" + jsonObject);//{"name":"张三","age":18,"sex":"男"}
}
}
2、Java对象–>JSON字符串
public class JSONTest{
public static void main(String[] args) {
USer user = new User("张三", "男", 18);
//Java对象转换成JSON字符串
String userStr = JSONObject.toJSONString(user);
System.out.println("Java对象转换成JSON字符串\n" + userStr);//{"age":18,"name":"张三","sex":"男"}
}
}
3、JSON对象–>JSON字符串
public class JSONTest{
public static void main(String[] args) {
User user = new User("张三", "男", 18);
//先转成JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
//JSON对象转换为JSON字符串
String jsonString = jsonObject.toJSONString();
System.out.println("JSON对象转换为JSON字符串\n" + jsonString);//{"name":"张三","age":18,"sex":"男"}
}
}
4、JSON对象–>Java对象
public class JSONTest{
public static void main(String[] args) {
User user1 = new User("张三", "男", 18);
//先转成JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user1);
//JSON对象转换成Java对象
User user = JSONObject.toJavaObject(jsonObject, User.class);
System.out.println("JSON对象转换成Java对象\n" + user);//User{name='张三', sex='男', age=18}
}
}
5、JSON字符串–>JSON对象
public class JSONTest{
public static void main(String[] args) {
String userStr = "{\"age\":18,\"name\":\"张三\",\"sex\":\"男\"}";
//JSON字符串转换成JSON对象
JSONObject jsonObject1 = JSONObject.parseObject(userStr);
System.out.println("JSON字符串转换成JSON对象\n" + jsonObject1);//{"sex":"男","name":"张三","age":18}
}
}
6、JSON字符串–>Java对象
public class JSONTest{
public static void main(String[] args) {
String userStr = "{\"age\":18,\"name\":\"张三\",\"sex\":\"男\"}";
//JSON字符串转换成Java对象
User user = JSONObject.parseObject(userStr, User.class);
System.out.println("JSON字符串转换成Java对象\n" + user);//user {name='张三', sex='男', age=18}
}
}