简体   繁体   中英

How to extract data from a json object in android

In my application I am receiving a JSON object as

{"secQueList":{"1":"Which is your favorite book?","2":"Who was your childhood hero?","3":"What is your pet's name?","4":"What make was your first car or bike?","5":"What is your favorite color?","6":"Which is your favorite sports team?","7":"What was the name of your school?","8":"What is your mother's maiden name?","9":"Which is your birthplace?","10":"Which is your favourite sport?","11":"Which is your favourite place of visit?"},"que1":null,"ans1":null,"message":null,"fieldErrors":null}

I am not able to figure out how exactly should i parse this object. I tried using the below code but as this not a JSONArray it throws an exception.

String getParam(String code, String element){
try {
       String base = this.getItembyID(code);
       JSONObject product = new JSONObject(base);
      JSONArray jarray = product.getJSONArray("item");
     String param =  jarray.getJSONObject(0).getString("name");
 return param;
} catch (JSONException e) {
    e.printStackTrace();
    return "error";
}
}
String base = this.getItembyID(code);
JSONObject product = new JSONObject(base);
JSONOBject secQueListJson = product.getJSONObject("secQueList");

// Get all json keys "1", "2", "3" etc in secQueList, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = secQueListJson .entrySet ();

Iterator iterator = entrySet.iterator ();

for (int j = 0; j < entrySet.size (); j++) {
    String key = null; //key = "1", "2", "3" etc
    try {
        Map.Entry entry = (Map.Entry) iterator.next ();
        key = entry.getKey ().toString ();
      //key = "1", "2", "3" etc
    }
    catch (NoSuchElementException e) {
        e.printStackTrace ();
    }
    if (!TextUtils.isEmpty (key)) {

        Log.d ("JSON_KEY", key);
        String value = secQueListJson.getString(key);
        //for key = "1", value = "Which is your favorite book?"
        //for key = "2", value = "Who was your childhood hero?"
    }
}

I recommend you use sites for json formater which show to you the types of json elements as http://json.parser.online.fr/ and you can use Gson library for parsing json by using pojo class

  public class secQueList {

  public String que1;

  public int ans1;

 public String message;

 public String nextPage;

 public QuestionList secQueList;

 }

public class QuestionList {
  @SerializedName("1")
  public String ques1;

  @SerializedName("2")
  public int ques2;

 @SerializedName("3")
 public String ques3;

 @SerializedName("4")
 public String ques4;

 @SerializedName("5")
 public String ques5;

 @SerializedName("6")
 public String ques6;

 @SerializedName("7")
 public int ques7;

 @SerializedName("8")
 public String ques8;

 @SerializedName("9")
 public String ques9;

 @SerializedName("10")
 public String ques10;

 @SerializedName("11")
 public String ques11;

 }

or you can use parse using built in JSON Object

  String jsonBody = the string you want to parse
  JSONObject quesJsonBody = new JSONObject(jsonBody);
  JSONOBject quesJson = quesJsonBody.getJSONObject("secQueList");
  String quesJson1 =  quesJson.getString("1");
  String quesJson2 =  quesJson.getString("2");
  String quesJson3 =  quesJson.getString("3");
  String quesJson4 =  quesJson.getString("4");
  String quesJson5 =  quesJson.getString("5");
  String quesJson6 =  quesJson.getString("6");
  String quesJson7 =  quesJson.getString("7");
  String quesJson8 =  quesJson.getString("8");
  String quesJson9 =  quesJson.getString("9");
  String quesJson10 = quesJson.getString("10");
  String quesJson11 = quesJson.getString("11");

  String que1 = quesJsonBody.getString("que1");
  String ans1 = quesJsonBody.getString("ans1");
  String message = quesJsonBody.getString("message");
  String fieldErrors = quesJsonBody.getString("fieldErrors");

Try something like this:

JSONObject jsonObject = new JSONObject(code);
JSONObject jsonObject1 = jsonObject.getJSONObject("secQueList");
for (int i=0;i<jsonObject1.length();i++){
 String msg = jsonObject1.getString(String.valueOf(i));
}

You can try to use Gson to parse it. I used code below in my App in similiar case:

ArrayList<String> myArrayList;
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<String>>(){}.getType();
myArrayList= gson.fromJson(code, type);

You have to add gson to your build.grandle to have it working

compile 'com.google.code.gson:gson:2.2.+'

Extract Data from JSON String

public void ReadSMS_JSON(String JSON_String) {
        String smsID = "";
        String phone = "";
        String message = "";

        JSONObject jsonResponse = new JSONObject(JSON_String);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("tblsms");
        if(jsonMainNode.length()>0){
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
            smsID = jsonChildNode.optString("sms_id");
            phone = jsonChildNode.optString("sms_number");
            message = jsonChildNode.optString("sms_message");
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM