注释文本可以全部删除,
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
把里面的包都加上就没事了
如有问题,随时可以留言