区别
JSONObject的数据是用 { } 来表明的,
例如: { "id" :1, "name" : "张一"}
JSONArray,是由JSONObject构成的数组,用 [ { } , { } , …… , { } ] 来表明
例如: [ { "id" :1, "name" : "张一"}, { "id" :2, "name" : "张二"}] ;
用法
people类
@Data
public class People {
private Integer id;
private String name;
public People(Integer id, String name) {
this.id = id;
this.name = name;
}
}
对象、JSON字符串相互转换
People people = new People(1, "张一");
//对象转String
String people2String = JSONObject.toJSONString(people);
//String转对象
People string2People = JSONObject.parseObject(people2String, People.class);
对象、JSONObject相互转换
People people = new People(1, "张一");
//对象转JSONObject
JSONObject people2JsonObject = (JSONObject) JSONObject.toJSON(people);
//JSONObject转对象
People jsonObject2People = JSONObject.toJavaObject(people2JsonObject, People.class);
List、对象相互转换
List<People> peopleList = new ArrayList<>();
peopleList.add(pnew People(2, "张一);
peopleList.add(new People(2, "张二"));
peopleList.add(new People(3, "张三"));
//List转JSONArray
JSONArray peoples2JsonArray = JSONArray.parseArray(JSON.toJSONString(peopleList));
//JSONArray转List
List<People> jsonArray2Peoples = JSONObject.parseArray(peoples2JsonArray.toJSONString(), People.class);
//List转String
String peoples2String = JSONArray.toJSONString(peopleList);
//String转List
List<People> string2Peoples = JSONObject.parseArray(peoples2String, People.class);
JSONArray循环遍历
方法一
List<People> peopleLists = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject peopleJsonObject = peoples2JsonArray.getJSONObject(i);
People peopleOne = new People(peopleJsonObject.getInteger("id"), peopleJsonObject.getString("name"));
peopleLists.add(peopleOne);
}
方法二
List<People> peopleLists = new ArrayList<>();
Iterator<Object> it = peoples2JsonArray.iterator();
List<JSONObject> list = new ArrayList<JSONObject>();
while (it.hasNext()) {
JSONObject jsonObj = (JSONObject) it.next();
People peopleOne = new People(jsonObj.getInteger("id"), jsonObj.getString("name"));
peopleLists.add(peopleOne);
}
遍历JSONObject
People people = new People(1, "张一");
JSONObject people2JsonObject = (JSONObject) JSONObject.toJSON(people);
for (Map.Entry entry : people2JsonObject.entrySet()) {
System.out.println(entry.getValue());
}
输出结果
1
张一
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...


