赞
踩
JSON.parseObject
是将Json字符串转化为相应的对象;
JSON.toJSONString
是将对象转化为Json字符串
两者主要用于前后台的数据传输过程中
使用前需要先导入该包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
将JSON字符串转为Bean对象
Java 对象 Student
@Data
@Accessors(chain = true)
public class Student {
private String name;
private int score;
}
将JSON字符串转为该对象
public class Main {
public static void main(String[] args) {
String jsonStudent = "{name:'yolo',score:90}";
Student student = JSON.parseObject(jsonStudent, Student.class);
System.out.println(student);
}
}
是将对象转化为Json字符串
public class Main {
public static void main(String[] args) {
Student student = new Student().setName("yolo").setScore(98);
String s = JSON.toJSONString(student);
System.out.println(s);
}
}
示例1:str = “{“name”:“Yolo”,“Address”:“Beijing”}”;
public class Main {
public static void main(String[] args) {
String str = "{\"name\":\"Yolo\",\"Address\":\"Beijing\"}";
JSONObject jsonObject = JSON.parseObject(str);
System.out.println(jsonObject.toString());
System.out.println(jsonObject.getString("name"));
System.out.println(str);
}
}
示例2:str2 = “{“name”:“Yolo”,“Address”:“Beijing”, “data”:{“id”: 123}}”
public class Main {
public static void main(String[] args) {
String str2 = "{\"name\":\"Yolo\",\"Address\":\"Beijing\", \"data\":{\"id\": 123}}";
JSONObject jsonObject2 = JSON.parseObject(str2);
System.out.println(jsonObject2.getString("data"));
System.out.println(JSON.parseObject(jsonObject2.getString("data")).getString("id"));
}
}
示例3:str3 = “{“name”:“Yolo”,“Address”:“Beijing”, “data”:[{“id”: 123},{“id”: 345}]}”;
public class Main {
public static void main(String[] args) {
String str3 = "{\"name\":\"Yolo\",\"Address\":\"Beijing\", \"data\":[{\"id\": 123},{\"id\": 345}]}";
JSONObject jsonObject3 = JSON.parseObject(str3);
System.out.println(jsonObject3.toString());
System.out.println(jsonObject3.toJSONString());
System.out.println("data " + jsonObject3.getString("data"));
JSONArray data = JSON.parseArray(jsonObject3.getString("data"));
for (Object d: data) {
System.out.println(d);
System.out.println(JSON.parseObject(d.toString()).getString("id"));
System.out.println(JSON.parseObject(String.valueOf(d)).getString("id"));
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。