日期:2014-05-17  浏览次数:20753 次

用java解析json字符串问题
Java code
{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"-8℃","temp2":"4℃","weather":"晴","img1":"n0.gif","img2":"d0.gif","ptime":"18:00"}}

请问这个怎么解析呢?

------解决方案--------------------
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


Java code

 public void getJSONObject(){
        JSONObject node = JSONObject.fromObject("{'weatherinfo':{'city':'北京','cityid':'101010100','temp1':'-8℃','temp2':'4℃','weather':'晴','img1':'n0'}}");
        List<Object>  nodes = new ArrayList<Object>();
   
        JSONArray jsons = JSONArray.fromObject(node.get("weatherinfo"));
        
        for (Object o : jsons)
        {
            JSONObject jsonNode = JSONObject.fromObject(o);
            List<Object> treeNodes = new ArrayList<Object>();
            treeNodes.add(jsonNode.getString("city"));
            treeNodes.add(jsonNode.getString("cityid"));
            treeNodes.add(jsonNode.getString("temp1"));
            treeNodes.add(jsonNode.getString("temp2"));
            //...
            nodes.add(treeNodes);
        }
    
    System.out.println(nodes);
    }