在Android上从URL检索JSON

时间:2011-04-07 08:07:37

标签: android json

我的手机APP在文字模式下完美下载内容。下面是一个代码来做到这一点。我调用Communicator类和exectueHttpGet:

URL_Data = new Communicator().executeHttpGet("Some URL");

public class Communicator {
public String executeHttpGet(String URL) throws Exception 
{
    BufferedReader in = null;
    try 
    {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
        HttpGet request = new HttpGet();
        request.setHeader("Content-Type", "text/plain; charset=utf-8");
        request.setURI(new URI(URL));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";

        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) 
        {
            sb.append(line + NL);
        }
        in.close();
        String page = sb.toString();
        //System.out.println(page);
        return page;
    } 
    finally 
    {
        if (in != null) 
        {
            try 
            {
                in.close();
            } 
            catch (IOException e)    
            {
                Log.d("BBB", e.toString());
            }
        }
    }
}
}

我所接受的是这个(URL的源代码):

[{"id_country":"3","country":"AAA"},{"id_country":"8","country":"BBB"},
{"id_country":"66","country":"CCC"},{"id_country":"14","country":"DDD"},
{"id_country":"16","country":"EEE"},{"id_country":"19","country":"FFF"},
{"id_country":"24","country":"GGG"},{"id_country":"33","country":"HHH"},
{"id_country":"39","country":"III"},{"id_country":"44","country":"JJJ"},
{"id_country":"45","country":"KKK"},{"id_country":"51","country":"LLL"},
{"id_country":"54","country":"MMM"},{"id_country":"55","country":"NNN"},
{"id_country":"57","country":"OOO"},{"id_country":"58","country":"PPP"},
{"id_country":"63","country":"RRR"},{"id_country":"65","country":"SSS"}]

此响应是一个字符串。在服务器上,它作为JSON对象输出(使用PHP),现在在我的Android PHP中,我希望将此字符串转换为JSON。这可能吗?

6 个答案:

答案 0 :(得分:14)

您收到的是InputStream中附加到StringBuffer并在结尾处转换为String的一系列字符 - 因此String的结果为好的:))

您想要的是通过org.json.*类(如

)对此字符串进行后处理
String page = new Communicator().executeHttpGet("Some URL");
JSONObject jsonObject = new JSONObject(page);

然后继续jsonObject。由于您收到的数据是一个数组,您实际上可以说

String page = new Communicator().executeHttpGet("Some URL");
JSONArray jsonArray = new JSONArray(page);
for (int i = 0 ; i < jsonArray.length(); i++ ) {
  JSONObject entry = jsonArray.get(i);
  // now get the data from each entry
}

答案 1 :(得分:2)

修改

为了进一步解决我之前链接到的问题,请使用此示例。把它放在一个返回JSONArray的函数中(这样你就可以遍历数组并使用array.getString)。这适用于大多数数据。它会将正确的压缩标头发送到Web服务器并检测gzip压缩结果。试试吧:

    URL url = new URL('insert your uri here');
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    urlConn.setRequestProperty("Accept-Encoding", "gzip");
    HttpURLConnection httpConn = (HttpURLConnection) urlConn;
    httpConn.setAllowUserInteraction(false);
    httpConn.connect();
    if (httpConn.getContentEncoding() != null) {
        String contentEncoding = httpConn.getContentEncoding().toString();
        if (contentEncoding.contains("gzip")) {
        in = new GZIPInputStream(httpConn.getInputStream());
        }
        // else it is encoded and we do not want to use it...
    } else {
        in = httpConn.getInputStream();
    }
    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayBuffer baf = new ByteArrayBuffer(1000);
    int read = 0;
    int bufSize = 1024;
    byte[] buffer = new byte[bufSize];
    while (true) {
        read = bis.read(buffer);
        if (read == -1) {
        break;
        }
        baf.append(buffer, 0, read);
    }
    queryResult = new String(baf.toByteArray());
    return new JSONArray(queryResult);

/结束编辑

尝试阅读我在这个问题上发布的解决方案:

Create list in android app

H个,

斯图

答案 2 :(得分:1)

使用org.json.JSONObject,如

JSONObject json = new JSONObject(oage);

需要注意的是响应只是“真实”或“错误”。可能想创建一个检测这些情况的util函数,否则只需加载JSONObject。

好的,在这种情况下你会使用JSONArray

JSONArray jsonArray = new JSONArray(page); 
for (int i = 0; i < jsonArray.length(); ++i) {
  JSONObject element = jsonArray.getJSONObject(i);
  ..... 
}

答案 3 :(得分:0)

您是否尝试将内容类型设置为application/json

答案 4 :(得分:0)

假设我们有一个名为发布

的POJO类
<select ng-model="ubrandname">
    <option ng-repeat="brandname in brandfunction" value="{{brandname}}">{{brandname}}</option>
</select>

答案 5 :(得分:-2)

只是尝试

... ///

JSONArray jsonArray = new JSONArray(responseString);

for(JSONObject jsonObject:jsonArray)      {       .........
      }

//// ..