0

I have a JSON array like this :

    [
      {"_id": {"$oid":"57e9e4b1f36d281c4b330509"}, "user": "edmtdev" },
      {"_id": {"$oid":"57e9e4cec2ef164375c4c292"}, "user": "admin1234" },
      {"_id": {"$oid":"57ea1b0ac2ef164375c5ff1e"}, "username": "admin34" }
   ]

This is my User.class, used to store all data:

 public class User{
       private Id id;
       private String user;

       public Id getId() {
          return id;
       }

       public void setId(Id id) {
          this.id = id;
       }

       public String getUser() {
          return user;
       }

       public void setUser(String user) {
          this.user = user;
       }
    }

And my Id.class, used to store the ID:

public class Id {

   private String $oid;

   public String get$oid() {
     return $oid;
   }


   public void set$oid(String $oid) {
     this.$oid = $oid;
   }
}

I am using GSON in Java to get my users as a List<User>:

   List<User> users = new ArrayList<User>();
   Gson gson = new Gson();
   Type listType = new TypeToken<List<User>>(){}.getType();
   users = gson.fromJson(s,listType);

The problem is, I get users with username but no ID, $oid is not registered. Can someone help me understanding what does not work in this piece of code ?

Community
  • 1
  • 1
EddyLee
  • 803
  • 2
  • 8
  • 26
  • Are you using CouchDB ? I think GSON does not registed `_id` as a field, but I'm not sure at all. Try `debug` mode with a breakpoint to check if you receive the right object. – Yassine Badache Sep 27 '16 at 08:18
  • Possible duplicate of [Google Gson - deserialize list object? (generic type)](http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type) – xenteros Sep 27 '16 at 08:18

2 Answers2

5

You must replace id in User class by:

private Id _id;

because your json is _id, not id. And your json string at the end is wrong, is user, not username

Numb
  • 155
  • 3
2
@SerializedName("_id")
private Id id;

This is another approach.
You can use this above annotation also.

leesc
  • 77
  • 6