Android parse JSON data into a HashTable?
I g开发者_StackOverflowet data from a web service as JSON data. The displayed data is shown in the image: it's basically a class called Questionnaire which has two properties which are QuestionnaireId and QuestionnaireName. So the web service method I call returns a collections of this class Questionnaire.
I am trying to parse this data to an HashTable which I am not able to. Kindly help me get this data parsed into a Hashtable<QuestionnaireId,QuestionnaireName>
.
i parse some json string with this method, hope helps you
public static Vector<MyObject> getImagesFromJson(String jos){
Vector<MyObject> images = null;
try{
JSONObject jo = new JSONObject(jos);
JSONArray array = jo.getJSONArray("images");
if(array != null && array.length() > 0){
images = new Vector<MyObject>();
}
for (int i=0;i<array.length();i++) {
MyObject object = new MyObject();
object.setEpigrafe( array.getJSONObject( i ).get( "epigrafe" ).toString() );
object.setId( array.getJSONObject( i ).getInt( "id" ) );
object.setUrl( array.getJSONObject( i ).get( "url" ).toString() );
images.add(object);
}
}catch(Exception e){
images = null;
e.printStackTrace();
}
return images;
}
where MyObjects is defined as:
private int id;
private String url;
private String epigrafe;
You'll want something along the lines of this:
Hashtable<Integer,String> table = new Hashtable<Integer,String>();
/* ... */
JsonObject root = new JsonObject(json_string);
JsonArray questions = root.getJsonArray("d");
for(int i = 0; i < questions.length(); i++) {
JsonObject question = questions.getJsonObject(i);
int id = question.optInt("QuestionnaireId", -1);
String name = question.optString("QuestionnaireName");
table.put(id, name);
}
(Roughly...)
You could easily ask google: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
I would recommend to not just stuff it into a Map but to map the data to POJOs and then fill a List with that POJOs.
Define your POJO like this.
public class Questionnaire {
private int id;
private String name;
public Questionnaire() {
setId(0);
setName(null);
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Create a List of Questionnaire
objects.
Now create a new Questionnaire
object every time you need one and map the parsed data to to it using the setters.
Once you are done with one Questionnaire
object add it to the List.
精彩评论