Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/198.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 解析JSONObject和JSONArray的最佳方法_Java_Android_Json_Parsing_Arrays - Fatal编程技术网

Java 解析JSONObject和JSONArray的最佳方法

Java 解析JSONObject和JSONArray的最佳方法,java,android,json,parsing,arrays,Java,Android,Json,Parsing,Arrays,因此,我正试图找出解析以下JSON URL的最有效方法,我将在Android上用Java进行此操作 JSONParser.java public class JSONParser { private static final Context context = null; static InputStream is = null; static JSONObject jarray = null; static JSONArray jarray2 = null; static String js

因此,我正试图找出解析以下JSON URL的最有效方法,我将在Android上用Java进行此操作

JSONParser.java

public class JSONParser {

private static final Context context = null;
static InputStream is = null;
static JSONObject jarray = null;
static JSONArray jarray2 = null;
static String json = "";

// constructor
public JSONParser() {

}
public JSONObject getJSONFromUrl2(String url) {

       StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse response = client.execute(httpGet);
          StatusLine statusLine = response.getStatusLine();
          int statusCode = statusLine.getStatusCode();
          if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
              builder.append(line);
            }
                //Recommended by Ted Hopp
                return new JSONObject(builder.toString());
          } else {
            Log.e("==>", "No Response, Check Your API KEY");
            Toast.makeText(context,"Error Response, Check your API Key", Toast.LENGTH_LONG).show();
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        } catch (JSONException e) {
        Log.e("JSON Parser Activity", url + e.toString());
    }
    // return JSON String
    return null;
}
现在我面临的主要问题是使用我的JSONParser活动的第2部分解析JSONObject

返回以下JSON

{
  "energy_month": 31132,
  "current_power": 1963,
  "modules": 24,
  "energy_today": 1577,
  "system_id": 165756,
  "energy_week": 215504,
  "source": "microinverters",
  "energy_lifetime": 1545467,
  "summary_date": "2013-05-03T00:00:00-07:00"
 }

   protected ArrayList<String> doInBackground(final String... args) {

            JSONParser jParser = new JSONParser();
             arrfortextviews=new ArrayList<String>();
            JSONObject json2 = jParser.getJSONFromUrl2(https://api.company.com/api/systems/165756/summary?&key=e1e63de7276b04c9bb99adfd45b3a14c);
                  //Added due to for some reason index return has more than 1
         for (int i = 0; i < json2.length(); i++) {
                        try {                       
                    Log.e("JSON Parser", summary + args.toString());
                    String current_power = json2.getString(TAG_CURRENT_POWER);
                    String energy_lifetime = json2.getString(TAG_ENERGY_LIFETIME);
看看这门课。它是标准Android发行版的一部分。代码可以简单到:

JSONObject thing = new JSONObject(jsonString);
然后,您只需浏览
thing
的对象结构即可获得所需的数据

您的
getJSONFromUrl2
方法可能如下所示:

public JSONObject getJSONFromUrl2(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return new JSONObject(builder.toString());
        } else {
            Log.e("==>", "No Response, Check Your API KEY");
            Toast.makeText(context,"Error Response, Check your API Key", Toast.LENGTH_LONG).show();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        Log.e("JSON Parser", json + url + e.toString());
    }
    return null; // only gets here on an error
}

它缺少一点错误处理,但由于您的原始代码也缺少它,我认为这是您最终将要做的工作。

您可以使用谷歌提供的截取库。
它有许多好处,如缓存、内存管理和排队请求。
您可以在这里找到一个最佳解决方案:

我建议不要在发出请求的同一异步任务中解析JSON。AsyncTask的响应和您的活动之间的一层可以有更细粒度的错误处理、跨请求的代码重用,以及记录连接问题、服务器错误、JSON解析错误等情况@iambmelton我已经更新了我的代码-您介意再看一眼吗谢谢您的回答,我正在使用一个JSONParser活动,我已经在上面发布了。我现在遇到的问题是,我无法使用
getJSONFromUrl2
而不是
getJSONFromUrl
@JaisonBrooksDevelopment使用我的JSONParser活动的第二部分解析JSONObject-您似乎已经注释掉了进行解析的代码。为什么你不能解析这个对象?您是否尝试过简单地
返回新的JSONObject(builder.toString());'在
try`block中,您的意思是这样的`try{//JSONObject jobj2=newjsonobject(builder.toString());returnnewjsonobject(builder.toString());//jarray=jobj2.getJSONObject(“summary”);}catch(JSONException e){}//return JSON String return jobj2`@JaisonBrooksDevelopment-我的意思是
try
块应该是一条语句:
返回新的JSONObject(builder.toString())。如果它抛出异常,您可以返回一个空的JSONObject
null
,或者带异常退出该方法。这完全取决于您希望如何处理调用代码中的错误。我在上面放置了一些更新的代码以及我当前的logcat问题-您介意仔细检查以确保我完全理解您。再次感谢泰德,谢谢你的资源。不久前,我通过使用GSON找到了一个解决方案。但是凌空抽射听起来真的很好用。你在这方面有很多经验吗?
public JSONObject getJSONFromUrl2(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return new JSONObject(builder.toString());
        } else {
            Log.e("==>", "No Response, Check Your API KEY");
            Toast.makeText(context,"Error Response, Check your API Key", Toast.LENGTH_LONG).show();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        Log.e("JSON Parser", json + url + e.toString());
    }
    return null; // only gets here on an error
}