Home > Mobile >  Issue when serializing JSON response into Java Object
Issue when serializing JSON response into Java Object

Time:08-08

Im a newbie in Java. I am trying to serialize a JSON response into a Java Object (UserData) but i am having some issues with the empty and null fields (even, i do not know the type of part of this data).

The JSON response is as follows:

    "id": 88,
    "username": "palomajim",
    "name": "Paloma Jimeno",
    "language": "en",
    "height": null,
    "isActive": true,
    "statistics": null,
    "tablets": [],
    "category": null,
    "role": null,
    "senior": [],
    "projects": null
}

As you can see, there are too many null and empty list fields. I am interesting in creating a Java Object that only considers the "id","username", "name","language" and "isActive" fields and that ignores the empty list and null fields.

Currently, my client class is as follows:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
 
@SpringBootApplication
public class RESTClient {

    static final String URL_NLP = "https://xxx/senior?by_senior_id=";
 
    public UserData getUserData(String idUser) {
 
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("x-api-key", "xxx");

        HttpEntity<User> entity = new HttpEntity<User>(headers);

        // RestTemplate
        RestTemplate restTemplate = new RestTemplate();

        // Send request with GET method, and Headers.
        ResponseEntity<UserData> response = restTemplate.exchange(URL_NLP idUser, HttpMethod.GET, entity, UserData.class);

        HttpStatus statusCode = response.getStatusCode();
        System.out.println("Response Satus Code: "   statusCode);
 
        // Status Code: 200
        if (statusCode != HttpStatus.OK) {
            return null;     
        }

        // Response Body Data
        UserData u = response.getBody();
            
        System.out.println("User name: "   u.getName());

        return u;

    }

And the class that represents UserData (the object where serializing the information in the JSON response is as follows):

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserData implements Serializable {

    private Integer id;
    private String username;
    private String name;
    private String language;
    private Boolean isActive;
    

    public UserData() {
    }

    public UserData(Integer id, String username, String name, String language) {
        this.id = id;
        this.username = username;
        this.name = name;
        this.language = language;

    }

    public Integer get_id() {
        return this.id;
    }

    public void set_id(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLanguage() {
        return this.language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public boolean getIsActive(){return this.isActive; }

    public void setIsActive(){this.isActive = isActive;}

    public UserData id(Integer id) {
        this.id = id;
        return this;
    }

    public UserData username(String username) {
        this.username = username;
        return this;
    }

    public UserData name(String name) {
        this.name = name;
        return this;
    }

    public UserData language(String language) {
        this.language = language;
        return this;
    }


    @Override
    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof UserData)) {
            return false;
        }
        UserData userData = (UserData) o;
        boolean b = Objects.equals(id, userData.id) && Objects.equals(name, userData.name)
                && Objects.equals(username, userData.username) && Objects.equals(language, userData.language) ;
        return Objects.equals(id, userData.id) && Objects.equals(name, userData.name) && Objects.equals(username, userData.username)
                && Objects.equals(language, userData.language);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, username, name, language);
    }

    @Override
    public String toString() {
        return "{"  
            " id='"   get_id().toString()   "'"  
            ", username='"   getUsername()   "'"  
            ", name='"   getName()   "'"  
            ", language='"   getLanguage()   "'"  
            ", isActive='"   ""   "'"  
            "}";
    }
}

However, i get the following error in the RESTClient class.

Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.springframework.http.ResponseEntity.toString()

Do you know what i am doing wrong? Should i proceed in another way in the UserData class? I do not know the type of the null fields and the empty list so it is not possible to consider them in the constructor of the UserData class. Could you help me?

CodePudding user response:

The exception speaks for itself, you're having a null pointer exception in the toString method. There is no need to use a .toString() on an Integer when contcatenating strings, you can change your toString() method like so:

@Override
public String toString() {
    return "{"  
        " id='"   get_id()   "'"  
        ", username='"   getUsername()   "'"  
        ", name='"   getName()   "'"  
        ", language='"   getLanguage()   "'"  
        ", isActive='"   ""   "'"  
        "}";
}

If we are talking instead of a more complex object, to avoid null pointers use String.valueOf(object). This specific method will print 'null' if the object is null and will instead call the .toString() method of the object if that is not null

  • Related