json的解析问题

版权声明:本文为博主原创文章,版权归原作者小思所有,转载或者引用本文内容请注明来源及原作者 https://blog.csdn.net/zeal9s/article/details/86086989

此博文以下列的json数据为例,讲解json转换或解析经常遇到的问题。

{
	"success": true,
	"resultMessage": "",
	"result": [{
		"code": "01",
		"level": 1,
		"orderSort": 1,
		"pcode": "0",
		"name": "配件",
		"isleaf": 0,
		"attrs": [{
			"param_code": "01",
			"sku": null,
			"param_name": "支腿",
			"param_value": "0-1000个",
			"params_type": 0,
			"unit": "个",
			"sort": 1,
			"type": 0,
			"category_group": "结构件",
			"group_sort": 3,
			"note": "配件类型中的支腿"
		}, {
			"param_code": "02",
			"sku": null,
			"param_name": "主电缆",
			"param_value": "0-100米",
			"params_type": 0,
			"unit": "米",
			"sort": 2,
			"type": 0,
			"category_group": "电气件",
			"group_sort": 3,
			"note": "配件类型中的主电缆"
		}]
	}],
	"resultCode": "5000"
}

此json数据涉及三个实体类,由外到内的顺序分别是
JsonRootBean–>Attrs–>Result

JsonRootBean.java

/**
  * Copyright 2019 bejson.com 
  */
package com.besjon.pojo;
import java.util.List;

/**
 * Auto-generated: 2019-01-08 17:30:27
 *
 * @author bejson.com ([email protected])
 * @website http://www.bejson.com/java2pojo/
 */
public class JsonRootBean {

    private boolean success;
    private String resultMessage;
    private List<Result> result;
    private String resultCode;
    public void setSuccess(boolean success) {
         this.success = success;
     }
     public boolean getSuccess() {
         return success;
     }

    public void setResultMessage(String resultMessage) {
         this.resultMessage = resultMessage;
     }
     public String getResultMessage() {
         return resultMessage;
     }

    public void setResult(List<Result> result) {
         this.result = result;
     }
     public List<Result> getResult() {
         return result;
     }

    public void setResultCode(String resultCode) {
         this.resultCode = resultCode;
     }
     public String getResultCode() {
         return resultCode;
     }

}

Attrs.java

/**
  * Copyright 2019 bejson.com 
  */
package com.besjon.pojo;

/**
 * Auto-generated: 2019-01-08 17:30:27
 *
 * @author bejson.com ([email protected])
 * @website http://www.bejson.com/java2pojo/
 */
public class Attrs {

    private String param_code;
    private String sku;
    private String param_name;
    private String param_value;
    private int params_type;
    private String unit;
    private int sort;
    private int type;
    private String category_group;
    private int group_sort;
    private String note;
    public void setParam_code(String param_code) {
         this.param_code = param_code;
     }
     public String getParam_code() {
         return param_code;
     }

    public void setSku(String sku) {
         this.sku = sku;
     }
     public String getSku() {
         return sku;
     }

    public void setParam_name(String param_name) {
         this.param_name = param_name;
     }
     public String getParam_name() {
         return param_name;
     }

    public void setParam_value(String param_value) {
         this.param_value = param_value;
     }
     public String getParam_value() {
         return param_value;
     }

    public void setParams_type(int params_type) {
         this.params_type = params_type;
     }
     public int getParams_type() {
         return params_type;
     }

    public void setUnit(String unit) {
         this.unit = unit;
     }
     public String getUnit() {
         return unit;
     }

    public void setSort(int sort) {
         this.sort = sort;
     }
     public int getSort() {
         return sort;
     }

    public void setType(int type) {
         this.type = type;
     }
     public int getType() {
         return type;
     }

    public void setCategory_group(String category_group) {
         this.category_group = category_group;
     }
     public String getCategory_group() {
         return category_group;
     }

    public void setGroup_sort(int group_sort) {
         this.group_sort = group_sort;
     }
     public int getGroup_sort() {
         return group_sort;
     }

    public void setNote(String note) {
         this.note = note;
     }
     public String getNote() {
         return note;
     }

}

Result.java

/**
  * Copyright 2019 bejson.com 
  */
package com.besjon.pojo;
import java.util.List;

/**
 * Auto-generated: 2019-01-08 17:30:27
 *
 * @author bejson.com ([email protected])
 * @website http://www.bejson.com/java2pojo/
 */
public class Result {

    private String code;
    private int level;
    private int orderSort;
    private String pcode;
    private String name;
    private int isleaf;
    private List<Attrs> attrs;
    public void setCode(String code) {
         this.code = code;
     }
     public String getCode() {
         return code;
     }

    public void setLevel(int level) {
         this.level = level;
     }
     public int getLevel() {
         return level;
     }

    public void setOrderSort(int orderSort) {
         this.orderSort = orderSort;
     }
     public int getOrderSort() {
         return orderSort;
     }

    public void setPcode(String pcode) {
         this.pcode = pcode;
     }
     public String getPcode() {
         return pcode;
     }

    public void setName(String name) {
         this.name = name;
     }
     public String getName() {
         return name;
     }

    public void setIsleaf(int isleaf) {
         this.isleaf = isleaf;
     }
     public int getIsleaf() {
         return isleaf;
     }

    public void setAttrs(List<Attrs> attrs) {
         this.attrs = attrs;
     }
     public List<Attrs> getAttrs() {
         return attrs;
     }

}

现在我们需要对这串json数据进行解析:

将字符串转换成JSONObject对象
核心代码:

String json="{\"param_code\":\"01\",\"sku\":null,\"param_name\":\"支腿\",\"param_value\":\"0-1000个\",\"params_type\":0,\"unit\":\"个\",\"sort\":1,\"type\":0,\"category_group\":\"结构件\",\"group_sort\":3,\"note\":\"配件类型中的支腿\"}";
JSONObject jsonObject =JSONObject.fromObject(json);
System.out.println(jsonObject);

运行控制台输出:

{"param_code":"01","sku":null,"param_name":"支腿","param_value":"0-1000个","params_type":0,"unit":"个","sort":1,"type":0,"category_group":"结构件","group_sort":3,"note":"配件类型中的支腿"}

将字符串转换成JSONArray对象
核心代码:

String json="[{\"param_code\":\"01\",\"sku\":null,\"param_name\":\"支腿\",\"param_value\":\"0-1000个\",\"params_type\":0,\"unit\":\"个\",\"sort\":1,\"type\":0,\"category_group\":\"结构件\",\"group_sort\":3,\"note\":\"配件类型中的支腿\"}]";
JSONArray jsonArray = JSONArray.fromObject(json);
System.out.println(jsonArray);

运行控制台输出:

[{"param_code":"01","sku":null,"param_name":"支腿","param_value":"0-1000个","params_type":0,"unit":"个","sort":1,"type":0,"category_group":"结构件","group_sort":3,"note":"配件类型中的支腿"}]

将字符串快速转换为Json对象
传统json拼接:

String areaJson="{\"id\": \"01\", \t\"level\": \"2\", \t\"pid\": \"0\", \t\"name\": \"永州\" }";
jsonObject jsonObject=JSONObject.fromObject(areaJson);

高效率拼接方式:

Area a=new Area();
a.setId("02");
a.setLevel(2);
a.setPid("0");
a.setName("上海");
//转换为json对象
Map<String,Object> map=new HashMap();
map.put("id",a.getId());
map.put("name",a.getName());
map.put("pid",a.getPid());
map.put("level",a.getLevel());
jsonObject jsonObject=JSONObject.fromObject(map);
//转换为json数组
List<Map<String,Object>> list=new ArrayList<>();
Map<String,Object> map1=new HashMap();
map.put("id",a.getId());
map.put("name",a.getName());
map.put("pid",a.getPid());
map.put("level",a.getLevel());
Map<String,Object> map2=new HashMap();
map2.put("id",a.getId());
map2.put("name",a.getName());
map2.put("pid",a.getPid());
map2.put("level",a.getLevel());
JSONArray jsonObject=JSONArray.fromObject(list);

将JSONObject、JSONArray变为字符串
核心代码:

String str=jsonObject.toString();
String str=jsonArray.toString();

向JSONObject存放键和值

核心代码:

JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "张三");
System.out.println(jsonObject1.toString());

将Collection对象转换成JSONArray对象, 本例为ArrayList

核心代码:

List<String> list = new ArrayList<String>();
list .add("uname");
list .add("upwd");
JSONArray jsonArray= JSONArray.fromObject(list );
System.out.println(jsonArray);

Map对象转换成JSONObject对象
核心代码:

Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
List<String> list = new ArrayList<String>();
list.add("student1");
list.add("student2");
map.put("teacher", list);
JSONObject jsonObject = JSONObject.fromObject(map);
System.out.println(jsonObject);

运行控制台输出:

{"teacher":["student1","student2"]}

将json数据中,值为数组的转换为List集合,以获取本文案例result键为例

//解析的对象数组
List objectList = new ArrayList<>();
JSONArray object_json = result_json.getJSONArray("result");

if (object_json.size() != 0) { //保存所有的数组,数组如果为空数组为数组将不能进行更新
    //将Json数组转换为json对象
    JSONObject jsonObject;
    Object obj;
    for (int i = 0; i < object_json.size(); i++) {
        jsonObject = JSONObject.fromObject(object_json.get(i).toString());
        obj = (Object) JSONObject.toBean(jsonObject, object.getClass());
        objectList.add(obj);
    }

}

列举JSONObject获取值的返回类型

//假设jsonObject是有数据的
JSONObject jsonObject = new JSONObject();

String uname = jsonObject.getString("uname");
boolean isDisabled = jsonObject.getBoolean("isDisabled");
double price = jsonObject.getDouble("price");
int age = jsonObject.getInt("age");
Object obj = jsonObject.getJSONObject("person");
Long l = jsonObject.getLong("price");

判断json数据是json对象还是json数组

//模拟JSONObject数据
String object_json ="{\"scm\":{\"key1\":\"vlaue1\",\"key2\":\"vlaue2\"}}";
//模拟JSONArray数据
String array_json = "{\"scm\":[{\"key1\":\"vlaue1\",\"key2\":\"vlaue2\"},{\"key3\":\"vlaue3\",\"key4\":\"vlaue4\"}]}";
//转换为json数据
JSONObject json = JSONObject.fromObject(array_json);

//通过scm键获取值
Object obj = new JSONTokener(json.getString("scm")).nextValue();
 if (obj instanceof JSONObject) { //json数据为JSONObject
    System.out.println("json为JSONObject");
    JSONObject jsonObject = (JSONObject) obj;
    System.out.println(jsonObject);

}
 if (obj instanceof JSONArray) { //json数据为JSONArray
    System.out.println("json为JSONArray");
    JSONArray jsonArray = (JSONArray) obj;
    for (int  i= 0;  i< jsonArray.size(); i++) {
        JSONObject parameterObject = jsonArray.getJSONObject(i);
        System.out.println(parameterObject);
    }
}

注意
1)net.sf.json.JSONObject

JSONObject是一个无序的键值对集合。值可以是任意类型:Boolean,JSONArray,JSONObject,Number,String,or the JSONObject.NULL Object

2)net.sf.json.JSONArray

JSONArray是一个有序的值序列。值可以是任意类型:Boolean, JSONArray, JSONObject, Number, String, or the JSONNull object。

3)JSONObject添加成员的方法element()与put()的区别:

put添加新成员:key是Object对象,value是Object对象
element添加新成员:key是String对象,value是JSONObject对象

4)关于json数据嵌套的,例如对象中套数组,数组中的对象信息又套数组,不管怎样变化,由外到内,依次转换为json的键所对应的对象,所以并不困难,重要的是对json数据的分析

博主整理了经常使用的,欢迎补充和斧正~

说在最后的话:编写实属不易,若喜欢或者对你有帮助记得点赞+关注或者收藏哦~

猜你喜欢

转载自blog.csdn.net/zeal9s/article/details/86086989