0

很长一段时间以来,我一直在尝试解析 JSON 对象。这里有很多类似的问题,但是没有一个有效的答案。我的代码都不是机密的,所以我在这里发布。

公共类 JSONParser {

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

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //HttpPost httpPost = new HttpPost(url);
            HttpGet httpget = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        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, "UTF-8"));
              //  is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {

            sb.append(line);
        }
        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 {
        JSONTokener tokener = new JSONTokener(json);
        jObj = new JSONObject(tokener);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

*edited Get 是必需的,而不是 Post

4

3 回答 3

0

我做了一个小测试应用程序并运行它。HTTPPost 不返回任何内容,但如果将其切换到 HTTPGet,则会得到有效响应。

之后,数组中的第一个元素缺少“名称”,因此当您调用时c.getString("name"),会生成一个 JSONException,看起来您只是在外部块中捕获。您需要为每个getString调用添加一些异常处理,可能类似于:

String name = null;
try {
name = c.getString("name");
} catch(JSONException e) {
//name is missing!
name = "";
}
于 2013-02-27T05:23:23.550 回答
0

我不明白你为什么要获取实体,将其转换为一次读取实体的 BufferedReader,将其转换为字符串,将字符串转换为 JSONTokener,然后最后使用标记器创建 JSONObject。

这是一个更简单的方法:

String entityString = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
JSONObject json = new JSONObject(entityString);

如果抛出异常,则使用输出捕获它:

} catch (Exception e) {
    e.printStackTrace();
}

并向我们​​展示那条痕迹。

于 2013-02-27T05:24:35.620 回答
0

不知道你的有什么问题,但也许与我一直在使用它的作品进行比较。我会说我有输入字符 0 错误,这是一个服务器端错误,而不是我的解析。这意味着返回的数据可能无法在 JSON 对象中编码。如果我没记错的话,我认为我的服务器没有返回任何内容,我基本上是在尝试解析nothing. 我会验证你从你的服务器得到什么。

String result;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key", "value");
nameValuePairs.add(new BasicNameValuePair("key2", "value2");

try
{
    HttpClient httpclient = new DefaultHttpClient();

            // URL to POST to
    HttpPost httpreq = new HttpPost("www.sample.com/file.php");
    httpreq.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httpreq);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();

    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();

    result = sb.toString();
            /* if you print 'result' you should see valid data 
               if your server is working */
            // System.out.println(result); 
}
catch (Exception e)
{
    // handle what went wrong
}

JSONArray jArray = new JSONArray(result);

if (jsonArray != null)
{
   for (int i = 0; i < jsonArray.length(); i++)
   {
       JSONObject json_data;
       try
       {
           json_data = jsonArray.getJSONObject(i);
           String value = json_data.getString("json_key_here");                
       }
       catch (JSONException e)
       {
            // handle what went wrong
       }
   }
}
于 2013-02-27T02:52:13.033 回答