有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从服务器读取json对象

嗨,我是安卓编程新手,我正在从事一个项目,该项目将列表转换为json对象,并将其存储在服务器中并检索它。我能够将json对象发送到服务器并存储它,但无法检索它。我应该使用什么方法来检索存储在服务器上的json对象


共 (2) 个答案

  1. # 1 楼答案

    要从服务器检索JSON,您必须首先使用DefaultHttpClient与服务器建立连接。希望您做到了。如果是,请发布代码,如果不是,请查看

    www.androidhive。info/2012/01/android json解析教程 或者在谷歌上搜索,当你有URL时,解析JSON会有很多帮助

  2. # 2 楼答案

    你可以参考下面的课程。。。。。。调用getJSONfromURL(您的_JOSN_URL),该方法将返回JSONObject。 我希望这能奏效

     public class JSONfunctions {
     public static JSONObject getJSONfromURL(String url) {
     InputStream is = null;
     JSONObject jObj = null;
     String json = "";
    // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            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"), 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 {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
      }
    
    }