Json转换:
1、Java对象-->Json对象:
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公众号BiggerBoy", "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字符串:
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公众号BiggerBoy", "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"}
}
}
3、Json对象-->Json字符串:
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公众号BiggerBoy", "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对象:
public class JSON2JavaTest{
public static void main(String[] args) {
Student stu = new Student("公众号BiggerBoy", "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对象:
public class JSON2JavaTest{
public static void main(String[] args) {
String stuString = "{\"age\":2,\"name\":\"公众号 BiggerBoy\",\"sex\":\"m\"}";
//JSON字符串转换成JSON对象
JSONObject jsonObject1 = JSONObject.parseObject(stuString);
System.out.println("JSON字符串转换成JSON对象\n" + jsonObject1);//{"sex":"m","name":"公众号编程大道","age":2}
}
}
6、Json字符串-->Java对象:
public class JSON2JavaTest{
public static void main(String[] args) {
String stuString = "{\"age\":2,\"name\":\"公众号 BiggerBoy\",\"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:
public class JSON2JavaTest{
public static void main(String[] args) {
String stuString = "[{\"age\":2,\"name\":\"公众号\",\"sex\":\"m\"},{\"age\":18,\"name\":\"BiggerBoy\",\"sex\":\"m\"}]";
//JSON字符串转换成Java对象
List<Student> studentList = JSONObject.parseArray(stuString, Student.class);
System.out.println("JSON字符串转换成Java对象list\n" +studentList ); } }
Comments 1 条评论
博主 xipei