skip to Main Content

OnResponse code :

card_list = new Gson().fromJson(_response, new TypeToken>>(){}.getType());


if (card_list.size() > 5) {

    recyclerview1.setAdapter(new Recyclerview1Adapter(card_list));

}else{

SketchwareUtil.showMessage(getApplicationContext(), _response);

}

Json 200 Result like :

{

  "user": [

    {

      "id": "string",

      "address": "string",

      "contact": "string",

      "name": "string",

      "description": "string",

      "image_url": ""

    }

  ],

  "next": "string"

}

But have the error when opening an activity :

BEGIN_ARRAY but was STRING at line 1 column 1

Please help me solve the code to retrieve json array to listmap for recyclerview in java android or sketchware

2

Answers


  1. If you know the JSON values, you can be explicit.

    Here is an example, where s is the String.

    Gson g = new Gson();
    Map<String, List<Map<String, String>>> m
        = g.<Map<String, List<Map<String, String>>>>fromJson(s, Map.class);
    
    System.out.println(m);
    

    Output

    {user=[{id=string, address=string, contact=string, name=string, description=string, image_url=}], next=string}
    

    If not, define the type-parameter as Object, and cast the Map value.

    Gson g = new Gson();
    Map<String, Object> m = g.<Map<String, Object>>fromJson(s, Map.class);
    
    @SuppressWarnings("unchecked")
    List<Map<String, Object>> users = (List<Map<String, Object>>) m.get("user");
    System.out.println(users);
    

    Output

    [{id=string, address=string, contact=string, name=string, description=string, image_url=}]
    
    Login or Signup to reply.
  2. The warning is there, Array was expected but found string, please show your response model for more context.
    From your json response model class or model data class, user should be an array like below.

    For Kotlin

    data class Data (
    
     @SerializedName("user" ) var user : ArrayList<User> = arrayListOf(),
     @SerializedName("next" ) var next : String?         = null
    
     )
    
    
    data class User (
      @SerializedName("id"          ) var id          : String? = null,
      @SerializedName("address"     ) var address     : String? = null,
      @SerializedName("contact"     ) var contact     : String? = null,
      @SerializedName("name"        ) var name        : String? = null,
      @SerializedName("description" ) var description : String? = null,
      @SerializedName("image_url"   ) var imageUrl    : String? = null
    )
    

    Java Should be:

     public class Data{
      public ArrayList<User> user;
      public String next;
     }
    
     public class User{
      public String id;
      public String address;
      public String contact;
      public String name;
      public String description;
      public String image_url;
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search