您可以为这个类实现自定义的反序列化器,但我认为更简单的解决方案是使用@JsonAnySetter注释。
class Teams {
Team team1 = new Team();
Team team2 = new Team();
@JsonAnySetter
public void anySetter(String key, String value) {
if (key.startsWith("team1")) {
team1.setId(key);
team1.setName(value);
} else if (key.startsWith("team2")) {
team2.setId(key);
team2.setName(value);
}
}
}
使用示例:
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = mapper.readValue(new File("X:/json"), Wrapper.class);
System.out.println(wrapper.getTeams());
}
}
class Wrapper {
private Teams teams;
public Teams getTeams() {
return teams;
}
public void setTeams(Teams teams) {
this.teams = teams;
}
}
上面的程序打印输出:
Teams [team1=Team [id=team1Id, name=team1Name], team2=Team [id=team2Id, name=team2Name]]
针对这个JSON:
{
"teams": {
"team1Id": "team1Name",
"team2Id": "team2Name"
}
}
如果你的JSON长这样:
{
"teams": {
"12345": "Chelsea",
"67890": "Tottenham"
}
}
我建议将其反序列化为
LinkedHashMap<String,String>
,然后将其转换为
Teams
对象。示例程序如下:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = mapper.readValue(new File("X:/json"), Wrapper.class);
System.out.println(wrapper.toTeams());
}
}
class Wrapper {
private LinkedHashMap<String, String> teams;
public LinkedHashMap<String, String> getTeams() {
return teams;
}
public void setTeams(LinkedHashMap<String, String> teams) {
this.teams = teams;
}
public Teams toTeams() {
List<Team> teamList = toTeamList();
Teams result = new Teams();
result.setTeam1(teamList.get(0));
result.setTeam2(teamList.get(1));
return result;
}
private List<Team> toTeamList() {
List<Team> teamList = new ArrayList<Team>(teams.size());
for (Entry<String, String> entry : teams.entrySet()) {
Team team = new Team();
team.setId(entry.getKey());
team.setName(entry.getValue());
teamList.add(team);
}
return teamList;
}
}
上面的程序输出:
Teams [team1=Team [id=12345, name=Chelsea], team2=Team [id=67890, name=Tottenham]]