You can implement custom deserializer for this class, but, I think, much simpler solution will be using @JsonAnySetter
annotation.
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);
}
}
//getters, setterr, toString()
}
Example usage:
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;
}
}
Above program prints:
Teams [team1=Team [id=team1Id, name=team1Name], team2=Team [id=team2Id, name=team2Name]]
for this JSON:
{
"teams": {
"team1Id": "team1Name",
"team2Id": "team2Name"
}
}
### EDIT 1 ###
If your JSON looks like that:
{
"teams": {
"12345": "Chelsea",
"67890": "Tottenham"
}
}
I propose to deserialize it to LinkedHashMap<String, String>
and after that convert it to Teams
object. Example program:
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;
}
}
Above program prints:
Teams [team1=Team [id=12345, name=Chelsea], team2=Team [id=67890, name=Tottenham]]