Json在android中解析

时间:2012-05-02 06:47:04

标签: java android web-services text-parsing

http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews

这是我的网络服务。我想解析它,我想要show news_id和新闻标题。请发帖,告诉我如何解析它,以便我可以将所有值存储在字符串中。我试过但是得到了Exception ..

try
    {
        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost("http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e)
    {
        Log.e("log_tag", "Error in http connection"+e.toString());
    }

    //convert response to string
    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line="0";
        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
    }catch(Exception e)
    {
        Log.e("log_tag", "Error converting result "+e.toString());
    }


//  String name;
    try
    {
        jArray = new JSONArray(result);
        JSONObject json_data=null;
        for(int i=0;i<jArray.length();i++)
        {
            HashMap<String, String> map = new HashMap<String, String>();
            json_data = jArray.getJSONObject(i);

//              name=json_data.getString("name");
            map.put("id",  String.valueOf(json_data.getString("news_id")));

            map.put("title",json_data.getString("news_title"));
            map.put("shortdescription",json_data.getString("news_short_description"));
            map.put("date",json_data.getString("news_date"));
            mylist.add(map);
        }


    }
        catch(Exception e)
    {
    }
}

2 个答案:

答案 0 :(得分:2)

您可以使用 Gson解析器进行解析。 首先从http://findjar.com/jar/com/google/code/gson/gson/1.1/gson-1.1.jar.html

下载 gson-1.1.jar 文件

然后将jar文件添加到项目构建路径中,然后使用下面的代码进行解析(使用下面的代码简单替换解析代码)

  try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        String  data = EntityUtils.toString(entity);

        Gson gson = new Gson();
        Type collectionType = new TypeToken<List<NewsData>>(){}.getType();
        List<NewsData> details = gson.fromJson(data, collectionType);
    }
    catch (Exception e) 
    {
        Log.i("error","error");
        e.printStackTrace();
    }

上面代码的bean是

public class NewsData
{
    private String news_id = null;
    private String news_title = null;
    private String news_short_description = null; 
    private String news_date = null;

    public String getNews_id()
    {
        return news_id;
    }
    public void setNews_id(String newsId)
    {
        news_id = newsId;
    }
    public String getNews_title()
    {
        return news_title;
    }
    public void setNews_title(String newsTitle)
    {
        news_title = newsTitle;
    }
    public String getNews_short_description()
    {
        return news_short_description;
    }
    public void setNews_short_description(String newsShortDescription)
    {
        news_short_description = newsShortDescription;
    }
    public String getNews_date()
    {
        return news_date;
    }
    public void setNews_date(String newsDate)
    {
        news_date = newsDate;
    }
}

并在清单中添加互联网权限

<uses-permission
        android:name="android.permission.INTERNET" />

我希望这会对你有所帮助。

答案 1 :(得分:1)

如果您仍未获得结果,可以使用以下代码。

static InputStream is = null;
    static JSONObject jObj = null;
    static JSONArray jsonArray=null;
    static String json = "";



mJsonArray=getJSONFromUrl(url);
        try{
        JSONObject mJsonObject=null;
        for(int i =0;i<mJsonArray.length();i++){
            if(!mJsonArray.isNull(i)){
                 HashMap<String, String> map = new HashMap<String, String>();
                 mJsonObject=mJsonArray.getJSONObject(i);
                 map.put("title",mJsonObject.getString("news_title"));
                 map.put("shortdescription",mJsonObject.getString("news_short_description"));
                 map.put("date",mJsonObject.getString("news_date"));
            //add you map in to list
            }
        }
        }catch(JSONException jexc){
            jexc.printStackTrace();
        }




public JSONArray getJSONFromUrl(String url) {

          // Making HTTP request
          try {
              // defaultHttpClient
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);

              HttpResponse httpResponse = httpClient.execute(httpPost);
              HttpEntity httpEntity = httpResponse.getEntity();
              is = httpEntity.getContent();            

          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }

          try {
              BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"), 8);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
              is.close();
              json = sb.toString();
          } catch (Exception e) {
              Log.e("Buffer Error", "Error converting result " + e.toString());
          }

          // try parse the string to a JSON object
          try {
            jsonArray =new JSONArray(json);
          } catch (JSONException e) {
              Log.e("JSON Parser", "Error parsing data " + e.toString());
          }

          // return JSON String
          return jsonArray;

      }