Levvy
Levvy

Reputation: 1150

Java JSON deserialize String with property names as field names

I am receiving from API json like that:

{
  "channel":"masta",
  "startTime":1427673600000,
  "endTime":1427760000000,
  "totalUniques":1,
  "totalViewtime":1927,
  "totalViews":13,
  "totalCountries":1,
  "countries":{
    "US":{
      "uniques":1,
      "views":13,
      "viewtime":1927
    }
  }
}

Now I want to deserialize it to class, so this class(Stats) will have fields like channel, startTime and so on. But how to handle countries property?

I thought about making class Countries but not sure about that cause it's have "US" as property name. Not "country": "US". And what's more it has own parameters. How to deserialize it?

Mostly I am using ObjectMapper object.readValue(jsonString) to do that but don't know how to handle 'countries'. In example is just one country 'US' but can be more.

Upvotes: 0

Views: 713

Answers (2)

Ken Bekov
Ken Bekov

Reputation: 14015

Declare Country class:

public class Country {
    private int uniques;
    private int views;
    private int viewtime;

    public int getUniques() {
        return uniques;
    }

    public void setUniques(int uniques) {
        this.uniques = uniques;
    }

    public int getViews() {
        return views;
    }

    public void setViews(int views) {
        this.views = views;
    }

    public int getViewtime() {
        return viewtime;
    }

    public void setViewtime(int viewtime) {
        this.viewtime = viewtime;
    }
}

In your Stats class you should declare countries as map of Country objects:

public class Stats {

   private String channel;
   private Long startTime;
   private Long endTime;    
   private int totalUniques;
   private int totalViewtime;
   private int totalViews;
   private int totalCountries;

   ...

   private Map<String, Country> countries;

   public Map<String, Country> getCountries() {
       return countries;
   }

   public void setCountries(Map<String, Country> countries) {
       this.countries = countries;
   }

}

Now you can deserialize you object:

ObjectMapper mapper = new ObjectMapper();
Stats stats = mapper.readValue(jsonString, Stats.class);

After deserialization your Stack object will get map with one Country object with key "US".

Upvotes: 1

Swapnil
Swapnil

Reputation: 8328

Basically, you need to define a POJO like ViewInfo that has the attributes like channel, startTime, endTime and so on. countries is also another attribute, but it isn't a primitive, it's like a map with country code as the key and Country as another POJO (which has attributes like uniques, views and so on). This way, you should be able to deserialize the json into this pojo.

Upvotes: 0

Related Questions