1. 程式人生 > >java讀取介面返回的json資料 (二)

java讀取介面返回的json資料 (二)

 註釋文字可以全部刪除,

java讀取 其他服務介面 返回的json資料

package cn.wangshiyu777;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;

import org.junit.Test;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



public class JsonUtil {
	public static String loadJson(String url) throws Exception {
		//讀取url,返回json串
		StringBuilder json = new StringBuilder();
		URL oracle = new URL(url);
		URLConnection yc = oracle.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
		String inputLine = null;
		while((inputLine = in.readLine()) != null){
			json.append(inputLine);
		}
		in.close();
		
		return json.toString();
	}
	public static void main(String[] args) throws Exception {
		String url = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo";
		//
		String json = loadJson(url);
		System.out.println(json);
		//獲取json字串中key對應的值
//		JsonParser jsonParser = new JsonParser();
		//將json字串轉化成json物件
//		JsonObject jObject = jsonParser.parse(json).getAsJsonObject();
		//獲取對應欄位值
//		String topic = jObject.get("Topic").getAsString();
//		System.out.println("Topic:"+topic);
		
//		第二種
//		JSONArray js = new JSONArray(json);
//		for (int i = 0; i < js.length(); i++) {
//			JSONObject json1 = js.getJSONObject(i);
//			System.out.println(json1.getString("Topic"));
//		}
		
		//第三種有錯
//		JSONObject jsonObject = JSON.parseObjet(json);
//		String r = jsonObject.getString("Topic");
//		System.out.println(r);
		
		//第四種
//		JSONObject json1 = new JSONObject(json);
//		String Value = json1.getString("Topic");
//		System.out.println(Value);
		
		JSONArray jsonArray = JSONArray.fromObject(json);

		//JSONArray jsonArray = JSONArray.fromObject(URLDecoder.decode(request.getParameter("rejectAry"),"UTF-8"));
		System.out.println(jsonArray);
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json1 = jsonArray.getJSONObject(i);
			System.out.println(json1.getString("Topic"));
		}
	}
	@Test
	public void aaa() throws UnsupportedEncodingException {
		String string  = new String("北京".getBytes("utf-8"),"unicode");
		String aString = new String(string.getBytes("unicode"), "utf-8");
		System.out.println(aString);
	}
}

 以下問題是我遇到的,記錄在下面

使用JSON,在SERVLET或者STRUTS的ACTION中取得資料時

如果會出現異常:java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher

原因是少了JAR包,造成類找不到

除了要匯入JSON網站上面下載的json-lib-2.1.jar包之外,

還必須有其它幾個依賴包:

commons-beanutils.jar

commons-httpclient.jar

commons-lang.jar

ezmorph.jar

morph-1.0.1.jar

把裡面的包都加上就沒事了

如有問題,隨時可以留言