日期:2014-05-20  浏览次数:21048 次

java怎么读取json数据呢
java怎么读取json数据呢

------解决方案--------------------
json最好用js读取,非常方便,就跟处理对象一样简单

Java code
package test;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class StrJson1 {

    public static void main(String[] args) {
        String json = "{'name': '呵呵','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'上海'}";
           try {
            JSONObject jsonObject = new JSONObject(json);
            String name = jsonObject.getString("name");
            String address = jsonObject.getString("address");

            System.out.println("name is:" + name);

            System.out.println("address is:" + address);
           
            JSONArray jsonArray = jsonObject.getJSONArray("array");
           
            for (int i = 0; i < jsonArray.length(); i++) {
             System.out.println("item " + i + " :" + jsonArray.getString(i));
                  try{
                     JSONObject jsonObject333 = new JSONObject(jsonArray.getString(i));
                    String aaaa = jsonObject333.getString("a");
                    System.out.println("----------"+aaaa);
                  }catch(Exception e){
                  }
            }
           } catch (JSONException e) {
            e.printStackTrace();
           }


    }
}

------解决方案--------------------
看个js的处理

XML code
{   
     userName: "nihao",   
     sex: "male",   
     age: "23"  
}

------解决方案--------------------
这里就是json字符串,还算比较复杂的一个了吧 {"icache":[{"cache_server_address":"10.88.53.198:11201","app_name":null,"cache_server_id":null,"token":null},{"cache_server_address":"10.88.53.198:11200","app_name":null,"cache_server_id":null,"token":null}]}

先到http://download.csdn.net/source/3512951下载jar包,然后

private static List<String> getListFromJson(String json) {

JSONObject ObjList;
List<String> list = new ArrayList<String>();
try {
ObjList = new JSONObject(json);
if (ObjList.has("icache")) {
JSONArray jArray = ObjList.getJSONArray("icache");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObj = (JSONObject) jArray.get(i);
list.add(jObj.getString("cache_server_address"));
}
}
} catch (Exception e) {
logger.error(e);
list = null;
} finally {
logger.info("ServerList is " + list);
return list;
}
}