如何判断 JSONObject 和 JSONArray

在实际开发中,经常需要将字符串、xml文件、或对象转换为 JSON 对象,以方便进行处理

但有时,我们并不知道要转换的对象是 JSONObject 还是 JSONArray;这时需要使用 org.json 包下的 JSONTokener 对象对要转换的对象进行判断,如果是 JSONObject,就转换为  JSONObject;如果是 JSONArray ,就转换为 JSONArray

 

先添加 org.json jar包


    org.json
    json
    20171018

 

判断的方法如下 (obj  为需要判断的对象)

Object resObj = new JSONTokener(obj.toString()).nextValue();//obj为需要判断的对象
		
if(resObj instanceof JSONObject) {
	System.out.println("对象是JSONObject: "+resObj);
}
		
if(resObj instanceof JSONArray) {
	System.out.println("对象是JSONArray: "+resObj);
}

 

测试示例

package com.jsondemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

public class Demo {

	public static void main(String[] args) {
		
		Map map = new HashMap();
		map.put("name", "bob");
		JSONObject jsonObject = new JSONObject(map);
		
		System.out.println(jsonObject);
		
		List list = new ArrayList();
		Map map1 = new HashMap();
		Map map2 = new HashMap();
		Map map3 = new HashMap();
		map1.put("name", "刘备");
		list.add(map1);
		map2.put("name", "关羽");
		list.add(map2);
		map3.put("name", "张飞");
		list.add(map3);
		JSONArray jsonArray = new JSONArray(list);
		
		System.out.println(jsonArray);
		
		
		//Object resObj = new JSONTokener(jsonObject.toString()).nextValue();
		Object resObj = new JSONTokener(jsonArray.toString()).nextValue();
		
		if(resObj instanceof JSONObject) {
			System.out.println("对象是JSONObject: "+resObj);
		}
		
		if(resObj instanceof JSONArray) {
			System.out.println("对象是JSONArray: "+resObj);
		}

	}

}

 

 

 

你可能感兴趣的:(json)