Parse json array android

后端 未结 3 1646
渐次进展
渐次进展 2020-12-06 12:59

Hi i\'m trying to parse json array from this url. The json array looks like this.

    [
   {
      \"id\":1,
      \"introtext\":\"\\u041b\\u0438\\u043c\\u04         


        
相关标签:
3条回答
  • 2020-12-06 13:42

    You can Easily do it using gson library.

    Here is the code sample:

    Your Entity Class will like:

    public class ResponseEntity {
        @SerializedName("id")
        public int id;
        @SerializedName("introtext")
        public String introtext;
        @SerializedName("image")
        public String image;
        @SerializedName("title")
        public String title;
        @SerializedName("catid")
        public String catid;
        @SerializedName("alias")
        public String alias;
    
    }
    

    Now Convert this json Array using GSON library.

    Gson gson=new Gson();    
        ResponseEntity[] entities = gson.fromJson(yourResponseAsString.toString(),
              ResponseEntity[].class);
    

    Now you have the entity array at entities.

    Thanks.

    0 讨论(0)
  • 2020-12-06 13:55

    you will need to make two changes in your current code according to string u have posted here for parsing as Json :

    First : change the return type of getJSONfromURL method to JSONArray and return JSONArray from it instead of JSONObject For example :

    public JSONArray getJSONfromURL(String url){
        String str_response="response from server";
    
        // convert response to JSONArray
       JSONArray json_Array=new JSONArray(str_response);
    
       return json_Array; //<< retun jsonArray
    }
    

    Second : change your code as for getting value from JsonArray :

    try {
        JSONfunctions j=new JSONfunctions();
        JSONArray jArray = j.getJSONfromURL(url);
        Log.i("log_tag", jArray.toString()); 
    
         for(int i=0;i<jArray.length();i++){
          JSONObject json_data = jArray.getJSONObject(i);
          String jsonvalues =  json_data.getString("id");
          // .. get all value here
          Log.i("DARE", jsonvalues);  
       }
      }
    catch (Exception ex)
       {
        Log.e("log_tag", "Error getJSONfromURL "+ex.toString());           
      }
    
    0 讨论(0)
  • 2020-12-06 14:00

    Of course it doesn't work! You should use json.getJSONArray(...) method for parsing arrays in Json :)

    0 讨论(0)
提交回复
热议问题