转
Java解析JSON格式的数据主要用到两个类JSONObject和JSONArray,这两个类在json-lib-2.4-jdk15包中,在使用JSONObject时除了需要这个包外还需要相关的依赖包
不导入这些包在运行时就会报错。
1.不包含数组的json数据,Java类的字段中也没有List。
现在有一个User类如下:
有两个字段id和name,json格式字符串如下:
String objectStr="{"name":"JAVA","id":"1"}";
将该字符串解析成对应的User类,代码如下所示:
import net.sf.json.JSONObject;
public class Demo {
public static void main(String[] args) {
String objectStr="{"name":"JAVA","id":"1"}";
JSONObject jsonObject = JSONObject.fromObject(objectStr);
User user = (User) JSONObject.toBean(jsonObject, User.class);
System.out.println(user.getId());
System.out.println(user.getName());
}
}
运行结果:
2.json数据为数组格式
import java.util.List;
import java.util.ArrayList;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Demo {
public static void main(String[] args) {
String arrayStr="[{"name":"JAVA","id":"1"}, {"name":"C#","id":"2"}]";
JSONArray jsonArray = JSONArray.fromObject(arrayStr);
List<User> list = new ArrayList<>();
for(int i = 0;i<jsonArray.size();i++) {
JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(i).toString());
User user = (User) JSONObject.toBean(jsonObject, User.class);
list.add(user);
}
for (User user : list) {
System.out.println("userID:" + user.getId() + " userName:" + user.getName());
}
}
}
3.接送数据中包含数组
这种情况直接解析会找不到对应的List类型,需要加一个classmap来确定类型,代码如下:
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Demo {
public static void main(String[] args) {
String ObjectStr="{"name":"JAVA","id":"1","goodsList":[{"name":"JAVA","id":"1"}, {"name":"C#","id":"2"}]}";
JSONObject jsonObject = JSONObject.fromObject(ObjectStr);
Map classmap = new HashMap<>();
classmap.put("goodsList", Goods.class);
User user = (User) JSONObject.toBean(jsonObject, User.class, classmap);
System.out.println(user.getId());
List<Goods> list = user.getGoodsList();
for (Goods goods : list) {
System.out.println("userID:" + goods.getId() + " userName:" + goods.getName());
}
}
}