注意来自不同3个jar包的JSONObject的区别
- com.alibaba.fastjson.JSONObject
- net.sf.json.JSONObject
- org.json.JSONObject
java对象和json数据之间的转换方式一般有两种,一种是引用第三方的jar包,如Gson(谷歌)、Fastjson(阿里)、Jackson等,这种方式优点是语法精练,可以实现一句话转化,但缺点是会引入庞大的第三方库,第二种是直接使用Java自带的org.json解析,但这个库功能比较基础,解析会写很多重复的代码
一 、com.alibaba.fastjson.JSONObject的使用
1 POM.xml
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
2 附上代码例子
2.1 创建2个实体类,供后面例子使用
public class School {
private String id;
private String name;
List<User> students = new ArrayList<User>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getStudents() {
return students;
}
public void setStudents(List<User> students) {
this.students = students;
}
}
public class User {
private String id;
private String name;
public User(){
}
public User(String id, String name){
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.2 Json字符串与Map、List、object之间的相互转换
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestFastJson {
public static void main(String[] args){
json2JsonObject();//将Json字符串转换为JSONObject对象
json2JavaBean();//将Json字符串转换为JavaBean对象
json2JsonArray();//将Json字符串转换为JSONArray对象
json2JavaBeanList();//将Json字符串转换为JavaBean的集合
javaBean2Json();//将JavaBean转换为Json格式的数据
javaBean2JsonObject();//将JavaBean转换为JSONObject对象
json2ListInMap();//从Json字符串的Map中获取List对象
list2JsonInMap();//将含list的Map对象转换为Json字符串
stringToMap();//json字符串转map
mapToString();//map转json字符串
mapToJsonObject();//map转json对象
testList2String();//list转json字符串
}
private static void json2JsonObject() {
String s = "{\"name\":\"peter\"}";
JSONObject object = JSON.parseObject(s);
System.out.println(object.get("name"));
}
private static void json2JavaBean() {
String s = "{\"id\":\"17051801\",\"name\":\"lucy\"}";
User user = JSON.parseObject(s, User.class);
System.out.println(user.getId());
System.out.println(user.getName());
}
private static void json2JsonArray() {
String s = "[{\"id\":\"17051801\",\"name\":\"lucy\"},{\"id\":\"17051802\",\"name\":\"peter\"}]";
JSONArray array = JSON.parseArray(s);
for (int i = 0; i < array.size(); i++) {
//JSONArray中的数据转换为String类型需要在外边加"";不然会报出类型强转异常!
String str = array.get(i)+"";
JSONObject object = JSON.parseObject(str);
System.out.println(object.get("name"));
}
}
private static void json2JavaBeanList() {
String s = "[{\"id\":\"17051801\",\"name\":\"lucy\"},{\"id\":\"17051802\",\"name\":\"peter\"}]";
List<User> list = JSON.parseArray(s, User.class);
for (User user : list) {
System.out.println(user.getName());
}
}
private static void javaBean2Json() {
User user = new User("17051801", "lucy");
String string = JSON.toJSONString(user);
System.out.println(string);
}
private static void javaBean2JsonObject() {
User user = new User("17051801", "lucy");
JSONObject json = (JSONObject) JSON.toJSON(user);
System.out.println(json.get("id"));
}
private static void json2ListInMap() {
String s = "{json:[{id:\"17051801\",\"name\":\"lucy\"},{id:\"17051802\",\"name\":\"peter\"},"
+ "{id:\"17051803\",\"name\":\"tom\"},{id:\"17051804\",\"name\":\"lily\"}]}";
//将Json字符串转换为JSONObject对象,并取出list对象的值
JSONObject object = JSON.parseObject(s);
Object objArray = object.get("json");
String str = objArray+"";
//方式1:转换成JSONArray对象形式
JSONArray array = JSON.parseArray(str);
for (int i = 0; i < array.size(); i++) {
JSONObject obj = JSON.parseObject(array.get(i)+"");
System.out.println(obj.get("name"));
}
//方式2:转换成List<JavaBean>形式
List<User> list = JSON.parseArray(str, User.class);
for (User user : list) {
System.out.println(user.getName());
}
}
private static void list2JsonInMap() {
//方式1:构建一个带有list的JavaBean对象
School school = new School();
school.setId("1");
school.setName("schoolA");
User user1 = new User();
user1.setId("17051801");
user1.setName("lucy");
User user2 = new User();
user2.setId("17051802");
user2.setName("peter");
school.getStudents().add(user1);
school.getStudents().add(user2);
//将JavaBean对象转换成Json字符串
String string1 = JSON.toJSONString(school);
System.out.println(string1);
//方式2:构建一个带有list的Map对象
Map<String, Object> map1 = new HashMap<String,Object>();
map1.put("id", "17051801");
map1.put("name", "lucy");
Map<String, Object> map2 = new HashMap<String,Object>();
map2.put("id", "17051802");
map2.put("name", "peter");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list.add(map1);
list.add(map2);
Map<String, Object> map = new HashMap<String,Object>();
map.put("id", "1");
map.put("name", "schoolA");
map.put("students", list);
//将map对象转换成Json字符串
String string2 = JSON.toJSONString(map);
System.out.println(string2);
}
private static void stringToMap(){
String str = "{\"age\":\"24\",\"name\":\"cool_summer_moon\"}";
JSONObject jsonObject = JSONObject.parseObject(str);
//json对象转Map
Map<String,Object> map = (Map<String,Object>)jsonObject;
System.out.println("map对象是:" + map);
Object object = map.get("age");
System.out.println("age的值是"+object);
}
private static void mapToString(){
Map<String,Object> map = new HashMap<>();
map.put("age", 24);
map.put("name", "cool_summer_moon");
String jsonString = JSON.toJSONString(map);
System.out.println("json字符串是:"+jsonString);
}
private static void mapToJsonObject(){
Map<String,Object> map = new HashMap<>();
map.put("age", 24);
map.put("name", "cool_summer_moon");
JSONObject json = new JSONObject(map);
System.out.println("Json对象是:" + json);
}
/**
* 测试包装类型的List转换为json字符串
*/
public static void testList2String() {
List<Long> longs = new ArrayList<Long>();
longs.add(1L);
longs.add(2L);
longs.add(3L);
String actual = JSON.toJSONString(longs);
Assert.assertEquals("[1,2,3]", actual);
}
}
二 、org.json.JSONObject的使用
1.引入org.json依赖
<!-- 引入org.json所需依赖 -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
2 构建JSONObject (3种)
2.1 直接构建
可以直接使用 new 关键字实例化一个JSONObject对象,然后调用它的 put() 方法对其字段值进行设置。
- 范例
JSONObject jsonObj = new JSONObject();
jsonObj.put("female", true);
jsonObj.put("hobbies", Arrays.asList(new String[] { "yoga", "swimming" }));
jsonObj.put("discount", 9.5);
jsonObj.put("age", "26");
jsonObj.put("features", new HashMap<String, Integer>() {
private static final long serialVersionUID = 1L;
{
put("height", 175);
put("weight", 70);
}
});
System.out.println(jsonObj);
- 结果
{
"features": {
"weight": 70,
"height": 175
},
"hobbies": ["yoga", "swimming"],
"discount": 9.5,
"female": true,
"age": 26
}
2.2 使用Map构建
- 范例
Map<String, Object> map = new HashMap<String, Object>();
map.put("female", true);
map.put("hobbies", Arrays.asList(new String[] { "yoga", "swimming" }));
map.put("discount", 9.5);
map.put("age", "26");
map.put("features", new HashMap<String, Integer>() {
private static final long serialVersionUID = 1L;
{
put("height", 175);
put("weight", 70);
}
});
JSONObject jsonObj = new JSONObject(map);
System.out.println(jsonObj);
- 结果
{
"features": {
"weight": 70,
"height": 175
},
"hobbies": ["yoga", "swimming"],
"discount": 9.5,
"female": true,
"age": 26
}
2.3 使用JavaBean构建
- 范例
import java.util.Map;
public class UserInfo {
private Boolean female;
private String[] hobbies;
private Double discount;
private Integer age;
private Map<String, Integer> features;
public Boolean getFemale() {
return female;
}
public void setFemale(Boolean female) {
this.female = female;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
public Double getDiscount() {
return discount;
}
public void setDiscount(Double discount) {
this.discount = discount;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Map<String, Integer> getFeatures() {
return features;
}
public void setFeatures(Map<String, Integer> features) {
this.features = features;
}
}
UserInfo userInfo = new UserInfo();
userInfo.setFemale(true);
userInfo.setHobbies(new String[] { "yoga", "swimming" });
userInfo.setDiscount(9.5);
userInfo.setAge(26);
userInfo.setFeatures(new HashMap<String, Integer>() {
private static final long serialVersionUID = 1L;
{
put("height", 175);
put("weight", 70);
}
});
JSONObject jsonObj = new JSONObject(userInfo);
System.out.println(jsonObj);
- 结果
{
"features": {
"weight": 70,
"height": 175
},
"hobbies": ["yoga", "swimming"],
"discount": 9.5,
"female": true,
"age": 26
}
3.解析JSONObject
JSONObject为每一种数据类型都提供了一个getXXX(key)方法,例如:获取字符串类型的字段值就使用getString()方法,获取数组类型的字段值就使用getJSONArray()方法。
- 范例
// 获取基本类型数据
System.out.println("Female: " + jsonObj.getBoolean("female"));
System.out.println("Discount: " + jsonObj.getDouble("discount"));
System.out.println("Age: " + jsonObj.getLong("age"));
// 获取JSONObject类型数据
JSONObject features = jsonObj.getJSONObject("features");
String[] names = JSONObject.getNames(features);
System.out.println("Features: ");
for (int i = 0; i < names.length; i++) {
System.out.println("\t"+features.get(names[i]));
}
// 获取数组类型数据
JSONArray hobbies = jsonObj.getJSONArray("hobbies");
System.out.println("Hobbies: ");
for (int i = 0; i < hobbies.length(); i++) {
System.out.println("\t"+hobbies.get(i));
}
- 结果
Female: true
Discount: 9.5
Age: 26
Features:
70
175
Hobbies:
yoga
swimming
三 net.sf.json.JSONObject的使用
1 引入maven依赖
最后一行需要保留,有两个jdk版本的实现:json-lib-2.1-jdk13.jar和json-lib-2.1-jdk15.jar
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
使用范例
JSONObject_1_3
package json;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
public class JSONObject_1_3 {
public static void javaToJSON() {
System.out.println("java代码封装为json字符串");
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", "张三");
jsonObj.put("password", "123456");
System.out.println("java--->json \n" + jsonObj.toString());
}
public static void jsonToJAVA() {
System.out.println("json字符串转java代码");
String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
JSONObject jsonObj = JSONObject.fromString(jsonStr);
String username = jsonObj.getString("username");
String password = jsonObj.optString("password");
System.out.println("json--->java\n username=" + username
+ "\t password=" + password);
}
public static void jsonToXML() {
System.out.println("json字符串转xml字符串");
String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
JSONObject json = JSONObject.fromString(jsonStr);
XMLSerializer xmlSerializer = new XMLSerializer();
xmlSerializer.setRootName("user_info");
xmlSerializer.setTypeHintsEnabled(false);
String xml = xmlSerializer.write(json);
System.out.println("json--->xml \n" + xml);
}
public static void javaBeanToJSON() {
System.out.println("javabean转json字符串");
UserInfo userInfo = new UserInfo();
userInfo.setUsername("张三");
userInfo.setPassword("123456");
JSONObject json = JSONObject.fromBean(userInfo);
System.out.println("javabean--->json \n" + json.toString());
}
public static void javaBeanToXML() {
System.out.println("javabean转xml字符串");
UserInfo userInfo = new UserInfo();
userInfo.setUsername("张三");
userInfo.setPassword("123456");
JSONObject json = JSONObject.fromBean(userInfo);
XMLSerializer xmlSerializer = new XMLSerializer();
String xml = xmlSerializer.write(json, "UTF-8");
System.out.println("javabean--->xml \n" + xml);
}
public static void xmlToJSON(){
System.out.println("xml字符串转json字符串");
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>张三</username></user_info>";
JSON json=XMLSerializer.read(xml);
System.out.println("xml--->json \n"+json.toString());
}
public static void main(String args[]) {
// javaToJSON();
// jsonToJAVA();
// jsonToXML();
// javaBeanToJSON();
// javaBeanToXML();
xmlToJSON();
}
}
UserInfo
package json;
public class UserInfo {
public String username;
public String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}