我正在尝试解析一个使用日期作为数组名称的JSON,因此它是可变的。如何使用Java / Spring做到这一点?
"Time Series (Daily)": {
"2018-08-21": {
"1. open": "106.9200",
"2. high": "107.2500",
"3. low": "106.8100",
"4. close": "107.0650",
"5. volume": "1156207"
},
"2018-08-20": {
"1. open": "107.5100",
"2. high": "107.9000",
"3. low": "106.4800",
"4. close": "106.8700",
"5. volume": "17914201"
},
要获取时间序列(每天),我正在使用:
@JsonProperty("Time Series (Daily)")
TimeSeries timeSeries;
但是使用TimeSeries对象做什么
@JsonProperty("2018-08-21")
Date date;
只会得到第一个吗?
答案 0 :(得分:0)
通过编写自定义解串器找到了解决方案。
时间序列类:
@JsonDeserialize(using = AvTimeSeriesDeserializer.class)
public class AvTimeSeries {
List<AvDay> avDays;
public List<AvDay> getAvDays() {
return avDays;
}
public void setAvDays(List<AvDay> avDays) {
this.avDays = avDays;
}
}
反序列化器:
public class AvTimeSeriesDeserializer extends StdDeserializer<AvTimeSeries> {
/**
*
*/
private static final long serialVersionUID = 1L;
public AvTimeSeriesDeserializer() {
this(null);
}
public AvTimeSeriesDeserializer(Class<?> vc) {
super(vc);
}
@Override
public AvTimeSeries deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
List<AvDay> avDays = new ArrayList<>();
JsonNode node = jp.getCodec().readTree(jp);
Iterator<Entry<String, JsonNode>> hello = node.fields();
hello.forEachRemaining(nodeA -> {
String date = nodeA.getKey();
JsonNode kappes = nodeA.getValue();
double open = kappes.get("1. open").asDouble();
double high = kappes.get("2. high").asDouble();
double low = kappes.get("3. low").asDouble();
double close = kappes.get("4. close").asDouble();
long volume = kappes.get("5. volume").asLong();
AvDay avDay = new AvDay(date, open, high, low, close, volume);
avDays.add(avDay);
});
AvTimeSeries result = new AvTimeSeries();
result.setAvDays(avDays);
return result;
}
}
这可能仍然可以进行优化,但是可以正常工作。