[英]Java JSON deserialize String with property names as field names
I am receiving from API json like that: 我从API json收到这样的:
{
"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. 现在,我想将其反序列化为类,因此该类(统计信息)将具有通道,startTime等字段。 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. 我曾考虑过将国家/地区设为类别,但不确定是否将其设为“ US”作为属性名称。 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'. 通常,我正在使用ObjectMapper object.readValue(jsonString)来执行此操作,但不知道如何处理“国家”。 In example is just one country 'US' but can be more.
例如,只有一个国家“美国”,但可以更多。
Declare Country
class: 声明
Country
类别:
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: 在您的
Stats
类中,您应该将countries
声明为Country
对象的地图:
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". 反序列化之后,您的
Stack
对象将获得一个键为“ US”的Country
对象的地图。
Basically, you need to define a POJO like ViewInfo that has the attributes like channel, startTime, endTime and so on. 基本上,您需要定义一个像ViewInfo这样的POJO,它具有诸如channel,startTime,endTime等属性。
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). countries
也是另一个属性,但它不是原始属性,它就像一张地图,其中以国家/地区代码为键,而国家/地区为另一个POJO(具有唯一性,视图等属性)。 This way, you should be able to deserialize the json into this pojo. 这样,您应该能够将json反序列化到此pojo中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.