I have this json response from a server.
{"session_key":"thekey","expires_in":300,"environment":"exttest","country":"SE","private_feed":{"hostname":"priv.api.test.nordnet.se","port":443,"encrypted":true},"public_feed":{"hostname":"pub.api.test.nordnet.se","port":443,"encrypted":true}}
The top level info is parsed fine into the below class. But how do I populate the list of server info?
The code
Response response = baseResource.path("login").queryParam("service", "NEXTAPI")
.queryParam("auth", authParam).request(responseType).post(null);
System.out.println(response);
SessionInfo ses = response.readEntity(SessionInfo.class);
public class SessionInfo {
public String session_key;
public String environment;
public int expires_in;
public String country;
List<ServerInfo> serverInfo = new ArrayList<ServerInfo>();
}
public class ServerInfo {
public String hostname;
public int port;
public boolean encrypted;
}
This works, but I would hope there is a way to convert it in one step since there might be more nested levels in other responses.
ObjectMapper mapper = new ObjectMapper();
ObjectNode json = response.readEntity(ObjectNode.class);
SessionInfo ses = mapper.treeToValue(json, SessionInfo.class);
ServerInfo s1 = mapper.treeToValue(json.get("private_feed"), ServerInfo.class);
ServerInfo s2 = mapper.treeToValue(json.get("public_feed"), ServerInfo.class);
ses.serverInfo.add(s1);
ses.serverInfo.add(s2);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…