Search code examples
javagsonjsonb

validate json with entity class


I have three classes like this :

public class User {
    private String username ;
    private String password;
} 

public class Profile extends User {
    private String name ;
    private String family ;
    private String age ;

}

public class AnotherProfileType {
    private String name ;
    private String family ;
    private String age ;
    private User user ;
}

and also i have a json string like this :

{
  "name":"Andy",
  "family":"Bypass",
  "age": 33,
  "username" : "andmand"
} 

and another json like this :

{
  "name": "Andy",
  "family": "Bypass",
  "age": "33",
  "user": {
    "username": "andmand"
  }
}

Note : you can see json has not password field . (This is only a example)
now i want to know which class is equivalent to this json .
we know first json matched by Profile class and second json matched by AnotherProfileType class . but how can validate (Understand) that ?

Update :
I need a code like this :

Object o = gson.fromJson(json,Object.class);
if (Object instanceof Profile) {
 // Do somethings 
}     

Object do not work in this example .
I want validate and match json to class with data structure.


Solution

  • I found a good answer :
    Map Json By Interface