0

JSON response:

{
  "id": "",
  "status": "",
  "Date": "",
  "Name": ""
}

When I try to map it with the class using object mapper.
Name of class is Demo with the field same in json response.
It mapped like:

Demo(id=, status=, Date=, Name=)

There are around 10-15 variables in the response.
I want to know if all the variables of Demo object are empty.

3
  • 1
    To start with, what JSON parser are you using, and where is your code? Please see How to Ask and minimal reproducible example.
    – kaya3
    Commented Mar 9, 2021 at 6:20
  • Just to understand your requirements: why do you want to know that?
    – GhostCat
    Commented Mar 10, 2021 at 8:22
  • You see, if making such checks is an important aspect of your work, then maybe: do use an object mapper. Instead have the response turned into a map for example, or well, something like a JsonNode, as pointed out in one of the answers. The point of an object mapper is to give you type safety. Which you give up when using reflection. And worse: you spent a lot of CPU cycles for nothing.
    – GhostCat
    Commented Mar 10, 2021 at 8:25

2 Answers 2

1

by using

JsonNode node = mapper.readTree(jString);

node.isNull();

you will get node is null or not using

node.get("id").isNull();
node.get("id").isEmpty(); 

you can verify the content of JsonNode

1
  • I agree, using a "raw" JsonNode class is better than doing mapping first, to then use reflection to get back to the fields.
    – GhostCat
    Commented Mar 10, 2021 at 8:23
1

A pure Java solution1 could be using reflection. Here a very simple implementation, mostly to show the idea (not complete, assuming fields are String, poor (no) exception handling):

public static boolean isEmpty(Demo demo) throws IllegalArgumentException, IllegalAccessException {
    for (var field : Demo.class.getDeclaredFields()) {
        if (field.getType() == String.class) {
            var value = (String) field.get(demo);
            if (value != null && !value.isEmpty()) {
                return false;
            }
        }
    }
    return true;
}

It could be improved for example by adding more types, using annotation on fields, ...

1: question is only tagged java
var was introduced in Java 10; use the concrete type (for (Field... or String value...) if using previous version of Java

2
  • Thanks, It worked. change type var field to Field field in for loop. Commented Mar 10, 2021 at 6:42
  • Just saying: of course reflection works, but depending on context, it is a rather weird approach to first use reflection to turn JSON into a distinct Java class, to then use reflection to somehow "reverse" that operation to get to all the fields.
    – GhostCat
    Commented Mar 10, 2021 at 8:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.