简体   繁体   English

将 JSON 响应序列化为 Java Object 时出现问题

[英]Issue when serializing JSON response into Java Object

Im a newbie in Java.我是 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). 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: JSON 响应如下:

    "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.如您所见,null 和空列表字段太多。 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.我对创建一个 Java Object 很感兴趣,它只考虑“id”、“用户名”、“名称”、“语言”和“isActive”字段,忽略空列表和 Z37A6259CC0C1DAE299ZBDBD48DBD48666666。

Currently, my client class is as follows:目前,我的客户 class 如下:

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):而代表UserData的class(object序列化JSON响应中的信息如下):

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.但是,我在 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?我应该在 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.我不知道 null 字段和空列表的类型,因此无法在 UserData class 的构造函数中考虑它们。 Could you help me?你可以帮帮我吗?

The exception speaks for itself, you're having a null pointer exception in the toString method.该异常不言自明,您在 toString 方法中有一个 null 指针异常。 There is no need to use a.toString() on an Integer when contcatenating strings, you can change your toString() method like so:连接字符串时无需在 Integer 上使用 a.toString() ,您可以像这样更改 toString() 方法:

@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) .如果我们正在谈论而不是更复杂的 object,为了避免 null 指针使用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如果 object 是 null,则此特定方法将打印“null”,并且如果不是 objectC4B666F8911C4B6666C4BD37A6ZDAE290C18DFF07A6Z866C40

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM