我刚开始在Android中使用JSON,并且遇到了一些从JSON创建模型对象的问题。如果有人知道任何好的教程或资源,可以查看更多细节,我真的很感激他们。到目前为止,我一直在关注Vogella和Bignerdranch 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对象是正确创建的,但是调查没有保存。知道我哪里错了吗?
public Survey(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString("id"));
if (json.has("title")) {
mTitle = json.getString("title");
}
}
一如既往,非常感谢任何帮助!
答案 0 :(得分:0)
原来问题是我试图将在JSON中发送的int id转换为UUID。
只要数据类型匹配,就可以正确创建项目。