我写了一个应该返回问题列表的网络服务 Web服务工作正常,我收到了JSON的响应。
JSON响应如下:
{
"QuestionList": [{
"answer": {
"options": ["Andriod is a phone", "Android is a language", "Android is a new fast food", "Android is Mobile App Development Tool"]
},
"id": "0",
"question": "What is Android?"
}, {
"answer": {
"options": ["No", "Yes"]
},
"id": "1",
"question": "Do you know Android?"
}, {
"answer": {
"options": ["No", "Yes", "Yes", "Yes"]
},
"id": "2",
"question": "Do you know Android?"
}, {
"answer": {
"options": ["Interface is contract for a class", "It is class", "It is an abstract class", "none of the above"]
},
"id": "3",
"question": "What is Interface?"
}, {
"answer": {
"options": ["Sonia Gandhi", "Rahul Gandhi", "Manmohan Singh", "Pratibha Patil"]
},
"id": "4",
"question": "Who is PM of India?"
}, {
"answer": {
"options": ["Haryana", "Delhi", "Deheradun", "Darjeling"]
},
"id": "5",
"question": "What is capital of India?"
}, {
"answer": {
"options": ["Abstract Class is a pre defined class", "Partial Implementation of a class", "A class that as have atleast 1 abstract method"]
},
"id": "6",
"question": "What is Abstract Class?"
}]
}
现在我必须将此响应转换为List
这是问题类
public class Question {
private int id;
private String question;
private Answer answer;
public Question() {
// TODO Auto-generated constructor stub
}
public Question(int id, String question, Answer answer) {
setId(id);
setQuestion(question);
setAnswer(answer);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public Answer getAnswer() {
return answer;
}
public void setAnswer(Answer answer) {
this.answer = answer;
}
@Override
public String toString() {
return "[ Question id: " + getId()
+ " Question: " + getQuestion()
+ " Answer: " + getAnswer() + " ]";
}
}
这是答案类
public class Answer {
private List<String> options;
public Answer() {
// TODO Auto-generated constructor stub
}
public Answer(List<String> options) {
setOptions(options);
}
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
@Override
public String toString() {
return "[ Options: " + getOptions() + " ]";
}
}
我无法弄清楚如何将响应转换为List 请帮忙......
答案 0 :(得分:2)
使用Gson:它将像
一样简单Gson gson = new GsonBuilder().create();
Answer a = gson.fromJson( response, Answer.class);
System.out.println( a );
Gson是一个功能强大的开源库,允许从POJO轻松映射到Json,反之亦然。
答案 1 :(得分:0)
使用此代码
Type collectionType = new TypeToken<List<Your_Object>>() {
}.getType();
List<Your_Object> your_Object = gson.fromJson(jsonString, collectionType);
希望这会对你有所帮助。