问题描述
我想将以下json映射到Java中的pojo。在下面显示的代码段中,result
是一个Json对象,其值是另一个json对象,它是一个映射。我尝试将其转换为Pojo,但失败了。 final_result :
{
"result":
{
"1597696140": 70.32,"1597696141": 89.12,"1597696150": 95.32,}
}
映射中的键是动态的,我无法事先猜到它们。
@JsonIgnoreProperties(ignoreUnkNown = true)
public class ResultData {
Map<Long,Double> resultMap;
public ResultData(Map<Long,Double> resultMap) {
this.resultMap = resultMap;
}
public ResultData() {
}
@Override
public String toString() {
return super.toString();
}
}
我创建的pojo是:
ObjectMapper objectMapper = new ObjectMapper();
ResultData resultData = objectMapper.readValue(resultData.getJSONObject("result").toString(),ResultData.class);
尝试使用ObjectMapper创建pojo时:
dat$Time <- as.Date(sprintf("%s-01",dat$Time))
group <- interaction(quarters(dat$Time),format(dat$Time,"%Y"))
data.frame(lapply(dat[-1],function(x) tapply(x,group,diff,lag = 2)))
TimeSeries1 TimeSeries2
Q1.1980 200 200
Q2.1980 200 200
Q3.1980 200 200
Q4.1980 200 200
在这里我可能做错什么了?
解决方法
假设,您的JSON
有效载荷如下所示:
{
"final_result": {
"result": {
"1597696140": 70.32,"1597696141": 89.12,"1597696150": 95.32
}
}
}
您可以将其反序列化为类:
@JsonRootName("final_result")
class ResultData {
private Map<Long,Double> result;
public Map<Long,Double> getResult() {
return result;
}
@Override
public String toString() {
return result.toString();
}
}
像下面这样:
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./src/main/resources/test.json");
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
ResultData resultData = mapper.readValue(jsonFile,ResultData.class);
System.out.println(resultData);
}
}
上面的代码打印:
{1597696140=70.32,1597696141=89.12,1597696150=95.32}
,
将JSONObject转换为Map并将地图设置为pojo字段,解决了该问题,并且没有导致我编写自定义反序列化器。
Map<Long,Double> resultData = objectMapper.readValue(resultData.getJSONObject("result").toString(),Map.class);
FinalResultData finaResultData = new FinalResultData(resultData);