我有以下JSON
,问题是Win the match
标签,因为空格:
{
"api": {
"results": 10,
"odds": {
"Win the match": {
"1": {
"label": "1",
"pos": "1",
"odd": "1.51"
},
"2": {
"label": "2",
"pos": "3",
"odd": "4.90"
},
"N": {
"label": "N",
"pos": "2",
"odd": "3.05"
}
}
}
}
}
在我的一个Java Class POJO
:
import com.fasterxml.jackson.annotation.JsonProperty;
public class OddsClass {
private The1_N22_EMT winTheMatch;
@JsonProperty("Win the match")
public The1_N22_EMT getWinTheMatch() { return winTheMatch; }
@JsonProperty("Win the match")
public void setWinTheMatch(The1_N22_EMT value) { this.winTheMatch = value; }
}
问题是此属性未正确映射。请,我需要你的帮助才能做出正确的映射。
JSON payload比你想象的要简单。对于动态键,请使用Map
。在你的情况下,你在Map
有Map
,因为你有两个级别的动态键。有时从POJO
生成的JSON
非常复杂。你应该从POJO
生成JSON Schema
模型。您的模型可能如下所示:
class ApiWrapper {
private Api api;
// getters, setters, toString
}
class Api {
private int results;
private Map<String, Map<String, Match>> odds;
// getters, setters, toString
}
class Match {
private String label;
private String pos;
private String odd;
// getters, setters, toString
}
你有两个棘手的案例:
JsonProperty
注释。Map<String, ?>
。POJO
模型的简单示例:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
ApiWrapper api = mapper.readValue(jsonFile, ApiWrapper.class);
System.out.println(api);
}
}
class ApiWrapper {
private Api api;
// getters, setters, toString
}
class Api {
private int results;
private Odds odds;
// getters, setters, toString
}
class Odds {
@JsonProperty("Win the match")
private Map<String, Match> winTheMatch;
// getters, setters, toString
}
class Match {
private String label;
private String pos;
private String odd;
// getters, setters, toString
}
也可以看看: