【问题标题】:Get the fields values from an Object type object (Spring)从 Object 类型对象 (Spring) 中获取字段值
【发布时间】:2020-06-16 23:10:14
【问题描述】:

在 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。

谢谢。

【问题讨论】:

    标签: java spring


    【解决方案1】:

    如果您无法更改上游函数以返回更有用的东西,因为它来自外部库或其他东西,那么创建 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',它不会实现 Serializable 并且需要包装在实现的类中。这是一个很好的解释:How to serialize a non-serializable in Java?

    供参考:

    【讨论】:

    • 如何导入JacksonUtil.toJsonNodeJsonNode actualObj = mapper.readValue(json, JsonNode.class); 不是更好的方法吗?
    • 使用 JsonNode 类型是不好的做法吗?我确实是从数据库中的另一个微服务返回对象,所以它是对象类型并且不能改变它
    • 听起来你可以创建一个类,从数据库或外部服务接收数据,并构造一个类的实例。这将是一个更好的方法。
    • 是的,无论如何都要使用 ParameterizedTypeReference,谢谢!
    【解决方案2】:

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

       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

    【讨论】:

    • 感谢您的回复,但已经得到了我想要的答案!
    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多