java - 解析 JSONObjects 和 JSONArrays 的最佳方式

标签 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 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 Activity 的第 2 部分解析 JSONObject。

https://api.company.com/api/systems/165756/summary?&key=e1e63de7276b04c9bb99adfd45b3a14c

返回以下 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);

但是使用当前代码我得到以下错误。

05-03 11:31:59.765: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.765: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.780: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.780: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.785: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.785: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.790: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.790: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.790: E/JSON - Parsing of Object 2nd Time in SummaryData.java(30625): {"energy_lifetime":1545467,"energy_today":12748,"current_power":4227,"energy_month":31132,"source":"microinverters","summary_date":"2013-05-03T00:00:00-07:00","energy_week":215504,"system_id":165756,"modules":24}[Ljava.lang.String;@41dfecd0
05-03 11:31:59.895: E/SpannableStringBuilder(30625): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
05-03 11:31:59.895: E/SpannableStringBuilder(30625): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

最佳答案

看看 JSONObject类(class)。它是标准 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
}

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

关于java - 解析 JSONObjects 和 JSONArrays 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362254/

相关文章:

java - Hadoop:客户端可以使用配置类设置的所有设置列表?

java - Spring 启动 : How to use WebClient instead of RestTemplate for Performing Non blocking and Asynchronous calls

java - Android TV Leanback Exoplayer 视频缩放问题

java - 声明一个局部变量并设置一次是否比一遍又一遍地使用 getter 更有效?

android - OpenGL ES 二维坐标

java - 启用加密和签名时 JWT 中的解析器异常

python - 带身份验证的网络 IPC(Python)

Java: "Cannot refer to a non-final variable inside an inner class [...]",OS X 和 Windows 之间的区别

android - 电话 : numeric keyboard for text input

javascript - AngularJS 待办事项列表应用程序 - 在页面刷新时保持列表