解析JSONObjects和JSONArrays的最佳方法

时间:2013-05-03 15:15:23

标签: 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;
}

现在主要的 ISSUE 正在使用我的JSONParser活动的第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

2 个答案:

答案 0 :(得分:1)

看一下JSONObject课程。它是标准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
}

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

答案 1 :(得分:1)

您可以使用谷歌提供的Volley库 它有许多好处,如缓存,内存管理和排队请求 你可以在这里找到一个最佳解决方案:
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/