1、Java对象–>JSON对象:
(JSONObject)JSONObject.toJSON(Java对象实例)
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公众号", "m", 2);
//Java对象转化为JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
System.out.println("Java对象转化为JSON对象\n" + jsonObject);//{"name":"编程","age":2,"sex":"m"}
}
}
2、Java对象–>JSON字符串
JSONObject.toJSONString(Java对象实例)
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公众y", "m", 2);
//Java对象转换成JSON字符串
String stuString = JSONObject.toJSONString(stu);
System.out.println("Java对象转换成JSON字符串\n" + stuString);//{"age":2,"name":"大道","sex":"m"}
}
}
3、JSON对象–>JSON字符串
JSONObject.toJSONString();
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公众oy", "m", 2);
//先转成JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
//JSON对象转换为JSON字符串
String jsonString = jsonObject.toJSONString();
System.out.println("JSON对象转换为JSON字符串\n" + jsonString);//{"name":"公大道","age":2,"sex":"m"
}
}
4、JSON对象–>Java对象
JSONObject.toJavaObject(JSON对象实例, Java对象.class);
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公erBoy", "m", 2);
//先转成JSON对象
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu);
//JSON对象转换成Java对象
Student student = JSONObject.toJavaObject(jsonObject, Student.class);
System.out.println("JSON对象转换成Java对象\n" + student);//Student{name='公众道', sex='m', age=2}
}
}
5、JSON字符串–>JSON对象
JSONObject.parseObject(JSON字符串)
public class JSON2JavaTest{
public static void main(String[] args) {
String stuString = "{\"age\":2,\"name\":\"公众 Big\",\"sex\":\"m\"}";
//JSON字符串转换成JSON对象
JSONObject jsonObject1 = JSONObject.parseObject(stuString);
System.out.println("JSON字符串转换成JSON对象\n" + jsonObject1);//{"sex":"m","name":"公众道","age":
}
}
6、JSON字符串–>Java对象
JSONObject.parseObject(JSON字符串, Java对象.class);文章来源:https://www.toymoban.com/news/detail-474213.html
public class JSON2JavaTest{
public static void main(String[] args) {
String stuString = "{\"age\":2,\"name\":\"公号 By\",\"sex\":\"m\"}";
//JSON字符串转换成Java对象
Student student1 = JSONObject.parseObject(stuString, Student.class);
System.out.println("JSON字符串转换成Java对象\n" + student1);//Student{name='公程大道', sex='m', age=2
}
}
7、JSON字符串–>List<Java对象>
List parseArray(JSON字符串, Java对象.class)文章来源地址https://www.toymoban.com/news/detail-474213.html
public class JSON2JavaTest{
public static void main(String[] args) {
String stuString = "[{\"age\":2,\"name\":\"公号\",\"sex\":\"m\"},{\"age\":18,\"name\":\"BirBoy\",\"sex\":\"m\"}]";
//JSON字符串转换成Java对象
List<Student> studentList = JSONObject.parseArray(stuString, Student.class);
System.out.println("JSON字符串转换成Java对象list\n" +studentList );
}
}
到了这里,关于fastjson--对象与JSON之间的转换方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!