日期:2014-05-16  浏览次数:20497 次

java解析json与map,list相互之间的转换

运行这个类需要加载jar包:ezmorph-1.0.6.jar、json-lib-2.4-jdk15.jar、jsoup-1.6.1.jar、commons-beanutils-1.8.0.jar、commons-collectio.jar、commons-lang-2.4.jar、commons-logging-1.1.1.jar。
点击下载所需夹包 http://download.csdn.net/detail/weizunde/7233825

 

package com.jjinfo.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

 

public class TestAction {

 public void sendMessage(String content) throws IOException {
  HttpServletResponse response = ServletActionContext.getResponse();
  response.setCharacterEncoding("UTF-8");
  //response.setCharacterEncoding("GBK");
  response.getWriter().write(content);
 }
  private static List<Map<String, String>> jsonStringToList(String rsContent) throws Exception
     {
         JSONArray arry = JSONArray.fromObject(rsContent);

         System.out.println("json字符串内容如下");
         System.out.println(arry);
         List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
         for (int i = 0; i < arry.size(); i++)
         {
             JSONObject jsonObject = arry.getJSONObject(i);
             Map<String, String> map = new HashMap<String, String>();
             for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();)
             {
                 String key = (String) iter.next();
                 String value = jsonObject.get(key).toString();
                 map.put(key, value);
             }
             rsList.add(map);
         }
         return rsList;
     }

 
 public String query() throws Exception{
  String str="";
  //获取xml,读入xml文件
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  System.out.println("----start----"+sdf.format(new Date()));
        URL url;
   
        url = new URL("http://star.sgst.cn/starInfoForZSCQ.do?systemName=ZSCQ&pageNum=6");
        URLConnection uc = url.openConnection();