英文:
How to consume a json array in java?
问题
我有这个实体Immobile:
public Integer usableAreas;
public String listingType;
public LocalDate createdAt;
public String listingStatus;
public Long id;
当进行请求时,我会获得大约10,000条数据,然而由于它是一个JSON数组,我不能直接使用RestTemplate,否则就必须将字符串转换为Immobile对象,这会增加很多工作量并且使代码变得混乱,是否有其他方法可以做到这一点?
public List<Immobile> getData() {
String response = restTemplate.getForObject(SOURCE_URL, String.class);
JSONArray jsonArray = new JSONArray(response);
List<Immobile> immobileList = new ArrayList<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
immobileList.add(new Immobile(
jsonArray.getJSONObject(i).getString("id"),
jsonArray.getJSONObject(i).getInt("usableAreas"),
jsonArray.getJSONObject(i).getString("listingType"),
jsonArray.getJSONObject(i).getDate("createdAt"),
jsonArray.getJSONObject(i).getString("listingStatus")
));
}
return immobileList;
}
英文:
I have this entity Immobile:
public Integer usableAreas;
public String listingType;
public LocalDate createdAt;
public String listingStatus;
public Long id;
When making the request I get about 10,000 data, however as it is a JSON ARRAY I can't use the rest template without having to convert String to immobile, and this takes a lot of work and makes the code ugly, is there another way for me do that?
public List<Immobile> getData() {
String response = restTemplate.getForObject(SOURCE_URL, String.class);
JSONArray jsonArray = new JSONArray(response);
List<Immobile> immobileList = new ArrayList<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
immobileList.add(new Immobile(jsonArray.getJSONObject(i).getString("id"),
jsonArray.getJSONObject(i).getInt("usableAreas"),
jsonArray.getJSONObject(i).getString("listingType"),
jsonArray.getJSONObject(i).getDate("createdAt"),
jsonArray.getJSONObject(i).getString("listingStatus")));
}
return immobileList;
}
答案1
得分: 0
另一种选择是使用ObjectMapper com.fasterxml.jackson.databind.ObjectMapper
。将映射到实体的操作将由ObjectMapper自身完成。
ObjectMapper objectMapper = new ObjectMapper();
List<Immobile> list = objectMapper.readValue(jsonString, new TypeReference<List<Immobile>>() { });
英文:
Other alternative is to use ObjectMapper com.fasterxml.jackson.databind.ObjectMapper
. Mapping to Entity will be done by ObjectMapper itself
ObjectMapper objectMapper = new ObjectMapper();
List<Immobile> list = objectMapper.readValue(jsonString, new TypeReference<List<Immobile>>() { });
答案2
得分: 0
尝试使用Gson库,它很容易使用。
Type token = new TypeToken<List<Immobile>>() {}.getType();
List<Immobile> immobileList = new Gson().fromJson(response, token);
英文:
Try Gson library, it's easy to use
Type token = new TypeToken<List<Immobile>>() {}.getType();
List<Immobile> immobileList = new Gson().fromJson(response, token);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论