无法获取变量来存储我已解析的jsonObjects

时间:2015-05-24 11:44:13

标签: java android arrays json string-parsing

我正在尝试将每个已解析的summaryJsonObject summariesJsonArray存储到变量storylineData中。我已经完成了代码,我可以看到原始json到达summaryJsonObject& summariesJsonArray但变量storylineData始终为null。我在下面提供了我的代码。我还想将在同一方法中解析的数据segment存储到变量storylineData中。 StorylineData是进行解析的类的名称以及json解析返回的变量。

StorylineData

   public class StorylineData {
        private static String date;
        private ArrayList<SummaryData> summary;
        private ArrayList<SegmentData> segments;
        private String caloriesIdle;
        private String lastUpdate;
    public String getDate() {
        return date;
    }
public ArrayList<SummaryData> getSummary() {
    return summary;
}

public ArrayList<SegmentData> getSegments() {
    return segments;
}

public String getCaloriesIdle() {
    return caloriesIdle;
}

public String getLastUpdate() {
    return lastUpdate;
}

public void setDate(String date) {
    this.date = date;
}

public void setSummary(ArrayList<SummaryData> summary) {
    this.summary = summary;
}

public void setSegments(ArrayList<SegmentData> segments) {
    this.segments = segments;
}

public void setCaloriesIdle(String caloriesIdle) {
    this.caloriesIdle = caloriesIdle;
}

public void setLastUpdate(String lastUpdate) {
    this.lastUpdate = lastUpdate;
}

public static StorylineData parse(JSONObject jsonObject) {
    if (jsonObject != null) {
        StorylineData storylineData = new StorylineData();
        storylineData.date = jsonObject.optString("date");
        storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
        storylineData.lastUpdate = jsonObject.optString("lastUpdate");
        storylineData.summary = new ArrayList<SummaryData>();
        storylineData.segments = new ArrayList<SegmentData>();
        JSONArray summariesJsonArray= jsonObject.optJSONArray("summary");
        if (summariesJsonArray != null) {
            for (int i = 0; i < summariesJsonArray.length(); i++) {
                JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
                if (summaryJsonObject != null) {
                    storylineData.summary.add(SummaryData.parse(summaryJsonObject));
                    Log.d("storylineHandler", summaryJsonObject.toString());
                }
            }
        }
        JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
        if (segmentsJsonArray != null) {
            for (int i = 0; i < segmentsJsonArray.length(); i++) {
                JSONObject segment = segmentsJsonArray.optJSONObject(i);
                if (segment != null) {
                    storylineData.segments.add(SegmentData.parse(segment));
                    Log.d("storylineHandler", segment.toString());
                }
            }
        }
        return storylineData;
    }
    return null;
}
}

HTTPCall

  public static void getDailyStorylineList(final MovesHandler<ArrayList<StorylineData>> handler,
                                             final String specificSummary,
                                             final String from,
                                             final String to,
                                             final String pastDays,
                                             final String updatedSince,
                                             final boolean needTrackPoints) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    /* Refresh access token if only AuthData.MOVES_REFRESHBEFORE days are there to expire current token */
                    AuthData.refreshAccessTokenIfNeeded();

                /* Exchange the authorization code we obtained after login to get access token */
                HashMap<String, String> nameValuePairs = new HashMap<String, String>();
                nameValuePairs.put("access_token", AuthData.getAuthData().getAccessToken());

               // if (specificSummary != null && specificSummary.length() > 0) nameValuePairs.put("specificSummary", specificSummary);//att

                if (from != null && from.length() > 0) nameValuePairs.put("from", from);
                if (to != null && to.length() > 0) nameValuePairs.put("to", to);
                if (pastDays != null && pastDays.length() > 0) nameValuePairs.put("pastDays", pastDays);
                if (updatedSince != null && updatedSince.length() > 0) nameValuePairs.put("updatedSince", updatedSince);
                if (needTrackPoints) nameValuePairs.put("trackPoints", "true");


                URL url     = new URL(MovesAPI.API_BASE + MovesAPI.API_PATH_STORYLINE + (specificSummary != null ? specificSummary : "") + "?" + Utilities.encodeUrl(nameValuePairs));
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoInput(true);
                urlConnection.connect();

                if (urlConnection.getResponseCode() != 200) {
                    /* All other HTTP errors from Moves will fall here */
                    handler.onFailure(getErrorStatus(Utilities.readStream(urlConnection.getErrorStream()), urlConnection.getResponseCode()), "Server not responded with success ("+ urlConnection.getResponseCode() +")");
                    return;
                }

                String response = Utilities.readStream(urlConnection.getInputStream());
                Object object = new JSONTokener(response).nextValue();
                if (object instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) object;
                    ArrayList<StorylineData> storylineData = new ArrayList<StorylineData>();
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject storylineJsonObject = jsonArray.optJSONObject(i);
                            if (storylineJsonObject != null) {
                                storylineData.add(StorylineData.parse(storylineJsonObject));
                            }
                        }
                    }
                    handler.onSuccess(storylineData);
                } else {
                    handler.onFailure(MovesStatus.INVALID_RESPONSE, "Expected a JSONArray from server, but failed");
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                handler.onFailure(MovesStatus.UNEXPECTED_ERROR, "An unexpected error occured, please check logcat");
            }
        }
    }).start();
}

SummaryData

public class SummaryData extends StorylineData {
    private String activity;
    private String group;
    private String duration;
    private String distance;
    private String steps;
    private String calories;

...getter/Setters...

public static SummaryData parse(JSONObject jsonObject) {
        if (jsonObject != null) {
                SummaryData summary = new SummaryData();
                summary.activity        = jsonObject.optString("activity");
                summary.group           = jsonObject.optString("group");
                summary.duration        = jsonObject.optString("duration");
                summary.distance        = jsonObject.optString("distance");
                summary.steps           = jsonObject.optString("steps");
                summary.calories        = jsonObject.optString("calories");
        //Log.d("json", summary.toString());

        return summary;
    }
    return null;
}
}

public class SegmentData {
    private String type;
    private String startTime;
    private String endTime;
    private PlaceData place;
    private ArrayList<ActivityData> activities;
    private String lastUpdate;

...getter/Setters...

public static SegmentData parse(JSONObject jsonObject) {
        if (jsonObject != null) {
            SegmentData segmentData = new SegmentData();
            segmentData.type        = jsonObject.optString("type");
            segmentData.startTime   = jsonObject.optString("startTime");
            segmentData.endTime     = jsonObject.optString("endTime");
            segmentData.lastUpdate  = jsonObject.optString("lastUpdate");

            JSONArray activitiesJSONArray = jsonObject.optJSONArray("activities");
            segmentData.activities = new ArrayList<ActivityData>();
            if (activitiesJSONArray != null) {
                for (int i = 0; i < activitiesJSONArray.length(); i++) {
                    JSONObject activityJsonObject = activitiesJSONArray.optJSONObject(i);
                    if (activityJsonObject != null) {
                        segmentData.activities.add(ActivityData.parse(activityJsonObject));
                    }
                }
            }

            JSONObject placeJsonObject = jsonObject.optJSONObject("place");
            if (placeJsonObject != null) {
                segmentData.place = PlaceData.parse(placeJsonObject);
            }

            return segmentData;
        }
        return null;
    }
}

示例Json

[
    {
        "date": "20121212",
        "summary": [
            {
                "activity": "walking",
                "group": "walking",
                "duration": 3333,
                "distance": 3333,
                "steps": 3333,
                "calories": 300
            },
            {
                "activity": "walking_on_treadmill",
                "group": "walking",
                "duration": 270,
                "steps": 303,
                "calories": 30
            },
            {
                "activity": "transport",
                "group": "transport",
                "duration": 1124,
                "distance": 8443
            },
            {
                "activity": "underground",
                "group": "transport",
                "duration": 1003,
                "distance": 8058
            },
            {
                "activity": "zumba",
                "duration": 570,
                "calories": 200
            }
        ],
        "segments": [
            {
                "type": "place",
                "startTime": "20121212T000000+0200",
                "endTime": "20121212T071430+0200",
                "place": {
                    "id": 1,
                    "type": "unknown",
                    "location": {
                        "lat": 55.55555,
                        "lon": 33.33333
                    }
                },
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "move",
                "startTime": "20121212T071430+0200",
                "endTime": "20121212T074617+0200",
                "activities": [
                    {
                        "activity": "walking",
                        "group": "walking",
                        "manual": false,
                        "startTime": "20121212T071430+0200",
                        "endTime": "20121212T072732+0200",
                        "duration": 782,
                        "distance": 1251,
                        "steps": 1353,
                        "calories": 99,
                        "trackPoints": [
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T071430+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T072732+0200"
                            }
                        ]
                    },
                    {
                        "activity": "transport",
                        "group": "transport",
                        "manual": false,
                        "startTime": "20121212T072732+0200",
                        "endTime": "20121212T074616+0200",
                        "duration": 1124,
                        "distance": 8443,
                        "trackPoints": [
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T072732+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T074208+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T074617+0200"
                            }
                        ]
                    }
                ],
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "place",
                "startTime": "20121212T074617+0200",
                "endTime": "20121212T100051+0200",
                "place": {
                    "id": 2,
                    "type": "unknown",
                    "location": {
                        "lat": 55.55555,
                        "lon": 33.33333
                    }
                },
                "activities": [
                    {
                        "activity": "walking_on_treadmill",
                        "group": "walking",
                        "manual": true,
                        "duration": 270,
                        "steps": 303,
                        "calories": 30,
                        "trackPoints": []
                    }
                ],
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "move",
                "startTime": "20121212T100051+0200",
                "endTime": "20121212T100715+0200",
                "activities": [
                    {
                        "activity": "walking",
                        "group": "walking",
                        "manual": false,
                        "startTime": "20121212T100051+0200",
                        "endTime": "20121212T100715+0200",
                        "duration": 384,
                        "distance": 421,
                        "steps": 488,
                        "calories": 99,
                        "trackPoints": [
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T100051+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T100715+0200"
                            }
                        ]
                    }
                ],
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "place",
                "startTime": "20121212T100715+0200",
                "endTime": "20121212T110530+0200",
                "place": {
                    "id": 4,
                    "name": "test",
                    "type": "foursquare",
                    "foursquareId": "4df0fdb17d8ba370a011d24c",
                    "foursquareCategoryIds": ["4bf58dd8d48988d125941735"],
                    "location": {
                        "lat": 55.55555,
                        "lon": 33.33333
                    }
                },
                "activities": [
                    {
                        "activity": "walking",
                        "group": "walking",
                        "manual": false,
                        "startTime": "20121212T101215+0200",
                        "endTime": "20121212T101255+0200",
                        "duration": 40,
                        "distance": 18,
                        "steps": 37,
                        "calories": 99,
                        "trackPoints": [
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T101215+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T101255+0200"
                            }
                        ]
                    }
                ],
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "move",
                "startTime": "20121212T110530+0200",
                "endTime": "20121212T111129+0200",
                "activities": [
                    {
                        "activity": "walking",
                        "group": "walking",
                        "manual": false,
                        "startTime": "20121212T110530+0200",
                        "endTime": "20121212T111128+0200",
                        "duration": 358,
                        "distance": 493,
                        "steps": 441,
                        "calories": 99,
                        "trackPoints": [
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T110531+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T110536+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T110947+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T111017+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T111129+0200"
                            }
                        ]
                    }
                ],
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "place",
                "startTime": "20121212T111129+0200",
                "endTime": "20121212T153638+0200",
                "place": {
                    "id": 2,
                    "type": "unknown",
                    "location": {
                        "lat": 55.55555,
                        "lon": 33.33333
                    }
                },
                "activities": [
                    {
                        "activity": "zumba",
                        "manual": true,
                        "duration": 570,
                        "calories": 200,
                        "trackPoints": []
                    }
                ],
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "move",
                "startTime": "20121212T153638+0200",
                "endTime": "20121212T160744+0200",
                "activities": [
                    {
                        "activity": "underground",
                        "group": "transport",
                        "manual": false,
                        "startTime": "20121212T153638+0200",
                        "endTime": "20121212T155321+0200",
                        "duration": 1003,
                        "distance": 8058,
                        "trackPoints": [
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T153638+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T155322+0200"
                            }
                        ]
                    },
                    {
                        "activity": "walking",
                        "group": "walking",
                        "manual": false,
                        "startTime": "20121212T155322+0200",
                        "endTime": "20121212T160744+0200",
                        "duration": 862,
                        "distance": 1086,
                        "steps": 1257,
                        "calories": 99,
                        "trackPoints": [
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T155322+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T155402+0200"
                            },
                            {
                                "lat": 55.55555,
                                "lon": 33.33333,
                                "time": "20121212T160744+0200"
                            }
                        ]
                    }
                ],
                "lastUpdate": "20130317T121143Z"
            },
            {
                "type": "place",
                "startTime": "20121212T160744+0200",
                "endTime": "20121212T232730+0200",
                "place": {
                    "id": 1,
                    "type": "unknown",
                    "location": {
                        "lat": 55.55555,
                        "lon": 33.33333
                    }
                },
                "lastUpdate": "20130317T121143Z"
            }
        ],
        "caloriesIdle": 1785,
        "lastUpdate": "20130317T121143Z"
    }
]

1 个答案:

答案 0 :(得分:0)

如果您可以使用第三方库,Jackson将非常有帮助。此Tutorial也解释了其他解决方案。