我在 jersey 客户端中使用 jackson 将 json 映射到 hashMap 但映射器也适用于 pojo。希望以下有所帮助。
将列表元素放入数组/列表中。循环并确定每个元素的正确类。
将每个列表元素及其各自的类名传递给处理映射并返回对象的方法。
import ...
import com.fasterxml.jackson.databind.ObjectMapper;
public class RequestProcessor {
void jerseyClient(){
//rest request
WebResource resource = ...
ClientResponse responseContent = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
List list = parseJSonResponse(responseContent);
for (String jsonListElement : list){
//determine correct class for jsonListElement
//Pass jsonListElement and class name to mapper method
Object obj = mapElementToObject(jsonListElement , className);
//do something with obj
}
}
private Object mapElementToObject(String jsonString, String className){
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(jsonString, Class.forName(className);
return obj;
}
private List parseJsonResponse(responseContent){
//use regexp to replace unnecessary content in response so you have a string
//that looks like -0:{element values}-1:{element values}-2:{element values}
//then split the string on "-.*\\:" into a array/list
//return the list
}
}