0

Under Java Spring boot, I have some returned object (of type Object) from a function having the following structure :

{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}

How to get the value of the id ? I tried converting it to JSONObject but it's not working, also i tried the reflection approach :

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

But it's not working either returns null.

Thank you.

lopmkipm
  • 67
  • 2
  • 10

2 Answers2

0

If you are unable to change the upstream function to return something more useful because it is from an external library or something, then creating a JsonNode (or similar) may be useful:

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();
}

If the type is actually just 'Object', it does not implement Serializable and will need to be wrapped in class that does. Here is a great explanation: How to serialize a non-serializable in Java?

For reference:

Thomas Portwood
  • 1,031
  • 8
  • 13
  • How to import `JacksonUtil.toJsonNode` ? isn't `JsonNode actualObj = mapper.readValue(json, JsonNode.class);` better approach ? – lopmkipm Jun 17 '20 at 00:04
  • Is it bad practice anyway to use JsonNode type ? i am indeed returning the Object from another microservices from a database so it is of type Object and cannot change that – lopmkipm Jun 17 '20 at 00:07
  • It sounds like you could create a class, receive the data from the database or external service, and construct an instance of the class. This would be a better approach. – Thomas Portwood Jun 17 '20 at 00:25
  • Yes using ParameterizedTypeReference anyway thank you! – lopmkipm Jun 17 '20 at 00:34
0

First, create a simple POJO having a single property id Person.java

   ObjectMapper mapper = new ObjectMapper();

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

If you fetch it using 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;

From this, you can retrieve only id from the JSON Object.

kkrkuldeep
  • 83
  • 5