当前位置: 首页 > 工具软件 > JSON lib > 使用案例 >

JSON教程之JSON-lib包方法解析(JAVA)

宁锐
2023-12-01

  目前大部分语言都支持JSON解析,我们这里说的是通过Java来解析JSON,目前支持Java解析的也有很多开源的项目,我们这里主要说说JSON-lib包解析和google-gson解析。本章为通过json-lib包来解析,如果需要了解其它语言和方法的解析,请去http://www.json.org/了解。

1、下载jar包

https://sourceforge.net/projects/json-lib/files/json-lib/  这个是json-lib的jar包

同时,这个jar包还依赖了一些其它的jar包,没有这些jar包程序也是不能运行的:

  • jakarta commons-lang 2.5   http://archive.apache.org/dist/commons/lang/binaries/
  • jakarta commons-beanutils 1.8.0 http://archive.apache.org/dist/commons/beanutils/binaries/
  • jakarta commons-collections 3.2.1 http://commons.apache.org/proper/commons-collections/download_collections.cgi
  • jakarta commons-logging 1.1.1 http://archive.apache.org/dist/commons/logging/binaries/
  • ezmorph 1.0.6  https://sourceforge.net/projects/ezmorph/files/ezmorph/ezmorph-1.0.6/

2、JSON中的类型与Java中的类型对应表

JSON   Java
string <=> java.lang.String, java.lang.Character, char
number <=> java.lang.Number, byte, short, int, long, float, double
true|false <=> java.lang.Boolean, boolean
null <=> null
function <=> net.sf.json.JSONFunction
array <=> net.sf.json.JSONArray (object, string, number, boolean, function)
object <=> net.sf.json.JSONObject
3、JSON解析实例

以一个JSON字符串为例,首先需要把JSON字符串转换为一个JSONObject对象

JSONObject rootObject=JSONObject.fromObject(jsonStr);

然后,需要根据JSON字符串的层次结构,依次解析其对应的元素。其中,主要的JSON元素
转换示例:

JSON --> Java(obj为一个JSONObject对象)

object  --> JSONObject regionObject=obj.getJSONObject("region");

string     -->  String name=obj.getString("name");

number -->Double latitudeDelta=obj.getDouble("latitude_delta");

true|false-->boolean isClaimed=obj.getBoolean("is_claimed");

array --> JSONArray businessArray=obj.getJSONArray("businesses");

array--> Object[] userBaseObjectArray=userBaseArray.toArray();//把JSONArray对象转换为Object[]

一个完整示例:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * json-lib解析例类
 * 主jar包:json-lib-2.4.jdk15.jar
 * 依赖的jar包:commons-beanutils-1.8.0.jar commons-collections-3.2.1.jar commons-lang-2.5.jar ezmorgh-1.0.6.jar
 * @author yuan
 *
 */
public class OfficialJSONAnalysed {
	/**
	 * 例子JSON解析,非通用
	 * @param jsonStr
	 */
	public static void analysedJSON(String jsonStr){
		JSONObject rootObject=JSONObject.fromObject(jsonStr);
		JSONArray businessArray=rootObject.getJSONArray("businesses");
			JSONObject businessObject=businessArray.getJSONObject(0);
				JSONArray categoryArray=businessObject.getJSONArray("categories");
					JSONArray firstCategoryArray=categoryArray.getJSONArray(0);
						String fca0=firstCategoryArray.getString(0);
						String fca1=firstCategoryArray.getString(1);
					JSONArray secondCategoryArray=categoryArray.getJSONArray(1);
						String sca0=secondCategoryArray.getString(0);
						String sca1=secondCategoryArray.getString(1);
				boolean isClaimed=businessObject.getBoolean("is_claimed");
				boolean isClosed=businessObject.getBoolean("is_closed");
				String name=businessObject.getString("name");
				String phone=businessObject.getString("phone");
				long dateUpdated=businessObject.getLong("menu_date_updated");
				JSONObject userObject=businessObject.getJSONObject("users");
					JSONArray userBaseArray=userObject.getJSONArray("user_base");
					Object[] userBaseObjectArray=userBaseArray.toArray();
					for(Object userBaseObject:userBaseObjectArray){
						JSONObject obj=(JSONObject) userBaseObject;
						String uname=obj.getString("name");
						String usex=obj.getString("sex");
						System.out.println(uname+"\t"+usex);
					}
		JSONObject regionObject=rootObject.getJSONObject("region");
			JSONObject centerObject=regionObject.getJSONObject("center");
				Double latitude=centerObject.getDouble("latitude");
				Double longitude=centerObject.getDouble("longitude");
			JSONObject spanObject=regionObject.getJSONObject("span");
				Double latitudeDelta=spanObject.getDouble("latitude_delta");
				Double longitudeDelat=spanObject.getDouble("longitude_delta");
		int total=rootObject.getInt("total");
		System.out.println(fca0+"\n"+fca1+"\n"+sca0+"\n"+sca1+"\n"+isClaimed+"\n"+isClosed+"\n"+name+"\n"+phone+"\n"+dateUpdated+"\n"+latitude+"\n"+longitude+"\n"+latitudeDelta+"\n"+longitudeDelat+"\n"+total);
	}
	

	public static void main(String[] args) {
		String jsonStr="{'businesses':[{'categories':[['Local Flavor','localflavor'],['Mass Media','massmedia']],'is_claimed':true,'is_closed':false," +
				"'name':'Yelp','phone':'4159083801','menu_date_updated':1317414369,'users':{'user_base':[{'name':'yuan','sex':'male'},{'name':'wang','sex'" +
				":'female'}]}}],'region':{'center':{'latitude':37.7861386,'longitude':-122.4026213},'span':{'latitude_delta':0,'longitude_delta':0}}," +
				"'total':10651}";
		OfficialJSONAnalysed.analysedJSON(jsonStr);
	}

}
/**
 *  example json string
 {
  "businesses": [
    {
      "categories": [
        [
          "Local Flavor",
          "localflavor"
        ],
        [
          "Mass Media",
          "massmedia"
        ]
      ],
      "is_claimed": true,
      "is_closed": false,
      "name": "Yelp",
      "phone": "4159083801",
      "menu_date_updated": 1317414369,
      "users": {
        "user_base": [
          {
            "name": "yuan",
            "sex": "male"
          },
          {
            "name": "wang",
            "sex": "female"
          }
        ]
      }
    }
  ],
  "region": {
    "center": {
      "latitude": 37.7861386,
      "longitude": -122.4026213
    },
    "span": {
      "latitude_delta": 0,
      "longitude_delta": 0
    }
  },
  "total": 10651
}

 * */





 类似资料: