There is the next json

{ "comments": { "4121585": { "counter": 185, "best": true }, "4121591": { "counter": 62 }, "4121595": { "counter": 59 }, "4121596": { "counter": 67 }, "4121599": { "counter": 19 } } } 

To him a class:

 public class Like implements Serializable { private Integer mCommentId; @SerializedName("counter") private Integer mCount; @SerializedName("best") private Boolean mIsBest; public Like() { this.mCommentId = 0; this.mCount = 0; this.mIsBest = false; } public Like(Integer commentId, Integer mCount, Boolean best) { this.mCommentId = commentId; this.mCount = mCount; this.mIsBest = best; } } 

Retrofit 2 code

  final Retrofit restAdapter = new Retrofit.Builder() .baseUrl("localhost") .addConverterFactory(GsonConverterFactory.create()) .build(); 

LikeService

 public interface LikeService { @Headers({ "Accept: application/json", "Content-type: application/json" }) @GET("/sdapi/news.api/{project}/posts/{post_id}/likes") Call<ArrayList<Like>> getLikes(@Path("project") String str1, @Path("post_id") String str2); } 

How to make the output so that finished objects are stored in ArrayList, according to {"4121585": {"counter": 185, "best": true}

4121585 - mCommentId

counter - mCount

best - mIsBest

Now it crashes with expx, as I understand it. Gson doesn’t know what to do with such json.

    2 answers 2

     public class Response { @SerializedName("comments") private Map<String, Comment> comments; public Map<String, Comment> getComments() { return comments; } public void setComments(Map<String, Comment> comments) { this.comments = comments; } } 

     public class Comment { @SerializedName("counter") private Integer mCount; @SerializedName("best") private Boolean mIsBest; public Comment() { this.mCount = 0; this.mIsBest = false; } } 

     Call<Response> getLikes(@Path("project") String str1, @Path("post_id") String str2); 

      Create, not ArrayList<Like> , but HashMap<String,Like> or you can override how the answer will be understood.

       Call<HashMap<String,Like>> getLikes(@Path("project") String str1, @Path("post_id") String str2); 
      • Yes, with this option does not fall, but it turns out that HashMap consists of 1 element. I think you need to somehow cut the comments block - user_21
      • @ user_21 you can always do anything you want from your mapy before writing to the database or wherever. - Eugene Suetin