从对象类型对象 (Spring) 获取字段值



在Java Spring引导下,我从具有以下结构的函数中返回了一些对象(类型为Object(:

{id=5, name=Jasmin, description=Room Jasmin, idType=0, addedAt=2020-06-16T17:20:00.617+0000, modifiedAt=null, deleted=true, images=[string],
idBuilding=2, idFloor=4, idZone=3}

如何获取 id 的值? 我尝试将其转换为 JSONObject,但它不起作用,我也尝试了反射方法:

Class<?> clazz = x.getClass();
Field field = clazz.getField("fieldName"); 
Object fieldValue = field.get(x);

但它也不起作用,返回 null。

谢谢。

如果您无法更改上游函数以返回更有用的内容,因为它来自外部库或其他内容,那么创建 JsonNode(或类似(可能会很有用:

try {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(x);
JsonNode jsonNode = mapper.readTree(json);
JsonNode idNode = jsonNode.get("id");
int id = idNode.asInt();
System.out.println("id = " + id);
}
catch (JsonProcessingException e) {
e.printStackTrace();
}

如果类型实际上只是"Object",则它不会实现可序列化,并且需要包装在具有可序列化功能的类中。这里有一个很好的解释:如何在 Java 中序列化不可序列化的?

供参考:

  • https://www.baeldung.com/jackson-object-mapper-tutorial

首先,创建一个具有单个属性idPerson 的简单 POJO.java

ObjectMapper mapper = new ObjectMapper();
// convertValue - convert Object of JSON to respective POJO class
GithubUsers githubUsers = mapper.convertValue(singleJsonData, Person.class);

如果您使用 RestTemplate 获取它:

List<GithubUsers> returnValue = new ArrayList<>();     
List<Object> listOfJsonData = restTemplate.getForObject("your-url", Object.class);
for (Object singleJsonData : listOfJsonData) {
ObjectMapper mapper = new ObjectMapper();
// convertValue - convert Object of JSON to respective POJO class
Person persons = mapper.convertValue(singleJsonData, Person.class);
returnValue.add(persons);
}
return returnValue;

由此,您只能从 JSON 对象中检索id

最新更新