0
我刚刚在Android中使用JSON,并且从JSON创建模型对象时遇到了一些问题。如果有人知道任何好的教程或资源,这将是很好的更多细节,我会很感激他们。到目前为止,我一直在关注Vogella和Bignerdranch Android书籍的教程。将JSON转换为模型对象Android
我能够拉入JSON并创建一个JSON对象,但是我的调查没有保存。
这里是我试图解析JSON:
[
{
"title": "Pepsi or Coke?",
"id": 1,
"questions": [
{
"id": 1,
"title": "Which pop do you prefer?",
"single_response": true,
"answers": [
{
"title": "Pepsi",
"id": 1
},
{
"title": "Coke",
"id": 2
},
{
"title": "Mountain Dew",
"id": 3
}
]
},
{
"id": 2,
"title": "What's your age?",
"single_response": true,
"answers": [
{
"title": "18-24",
"id": 4
},
{
"title": "25-34",
"id": 5
},
{
"title": "35-50",
"id": 6
},
{
"title": "50+",
"id": 7
}
]
},
{
"id": 3,
"title": "What's your political association?",
"single_response": true,
"answers": [
{
"title": "Republican",
"id": 8
},
{
"title": "Democrat",
"id": 9
}
]
}
]
}
]
我检索像这样JSON:
byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrl(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
这里的地方我分析它:
public ArrayList<Survey> getSurveys(String apiKey) throws JSONException {
ArrayList<Survey> surveys = new ArrayList<Survey>();
try {
String url = Uri.parse(ENDPOINT).buildUpon().appendQueryParameter("auth_token", apiKey).build().toString();
String jsonString = getUrl(url);
Log.i(TAG, "Received json string: " + jsonString);
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i ++) {
JSONObject object = array.getJSONObject(i);
Log.i(TAG, "Object is: " + object.toString());
}
for (int i = 0; i < array.length(); i++) {
Survey survey = new Survey(array.getJSONObject(i));
surveys.add(survey);
Log.i(TAG, "Survey is: " + survey.toString());
}
} catch (Exception e) {
Log.e(TAG, "Survey didn't save");
}
} catch (IOException ioe) {
Log.e(TAG, "Failed to retrieve surveys: " + ioe);
}
return surveys;
}
我假设问题出在我创建的调查方法本身,因为JSON对象创建正确,但调查不是s AVING。任何想法,我要去哪里错了?
public Survey(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString("id"));
if (json.has("title")) {
mTitle = json.getString("title");
}
}
与往常一样,任何帮助都非常感谢!