Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json String to Java Object with dynamic key name

Tags:

java

json

jackson

I'm trying to parse this structured of json string to Java Object but I failed every attempt.

{
  "message": "Test Message",
  "status": true,
  "users": {
    "user_xy": [
      {
        "time": "2016-08-25 19:01:20.944614158 +0300 EEST",
        "age": 24,
        "props": {
          "pr1": 197,
          "pr2": 0.75,
          "pr3": 0.14,
          "pr4": -0.97
        }
      }
    ],
    "user_zt": [
      {
        "time": "2016-08-25 17:08:36.920891187 +0300 EEST",
        "age": 29,
        "props": {
          "pr1": 1.2332131860505051,
          "pr2": -0.6628148829634317,
          "pr3": -0.11622442112006928
        }
      }
    ]
  }
}

props field can contain 1 properties or 6 properties, it depends on db record. Also Username part dynamically changing.

Can I parse successfully this structured string with Jackson Lib?

like image 846
Black Glix Avatar asked Dec 14 '22 04:12

Black Glix


1 Answers

You have to create calss structure like bellow to map your string to java object.

Create one class for Details

public class Details {
    private String message;
    private String status;
    private Map<String, List<UserDetails>> users = new HashMap<String, List<UserDetails>>();
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public Map<String, List<UserDetails>> getUsers() {
        return users;
    }
    public void setUsers(Map<String, List<UserDetails>> users) {
        this.users = users;
    }
}

Create UserDetails class like bellow.

public class UserDetails {
    private String time;
    private String age;
    private Map<String, String> prop = new HashMap<String, String>();
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public Map<String, String> getProp() {
        return prop;
    }
    public void setProp(Map<String, String> prop) {
        this.prop = prop;
    }   
}

Now you can map your string with Details class.

Hope this will help..

like image 196
Nirav Chhatrola Avatar answered Dec 17 '22 00:12

Nirav Chhatrola