【问题标题】:Java JsonIgnore is not hiding fieldJava JsonIgnore 没有隐藏字段
【发布时间】:2021-10-25 11:04:51
【问题描述】:

需要对 Json 隐藏一个字段,但保留它,因为需要在另一种方法中使用它(get)。尝试这样做,但 id 字段在 Json 中仍然可见。这里有什么问题?

依赖关系:

<properties>
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.4.4</jackson.version>
</properties>
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>catalina</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>8.0.53</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.bundles/jaxrs-ri -->
        <dependency>
            <groupId>org.glassfish.jersey.bundles</groupId>
            <artifactId>jaxrs-ri</artifactId>
            <version>2.31</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
</dependencies>

尝试这样做: 打包 test.model;

import java.math.BigDecimal;

import test.model.DbTest;

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

@JsonIgnoreProperties(value = { "id" })
public final class Home {
    @JsonIgnore
    private final BigDecimal id;

    private final String date;

    public Home( //
            BigDecimal id, //
            String date) {
        this.id = id;
        this.date = date;
    }

    public final BigDecimal getId() {
        return id;
    }

    public final String getDate() {
        return date;
    }
    
    public static final Home newInstance( 
            DbTest test) {
        return new Home( 
                test.getId(), 
                test.getDate());
    }
}

【问题讨论】:

  • 你试过把@JsonIgnore 放在getter 上吗?
  • 我尝试在getId 之前添加它,但它仍然不起作用..

标签: java json


【解决方案1】:

尝试在 pom.xml 中使用它

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.12.4</version>
</dependency>

或从字段中删除“final”

【讨论】:

猜你喜欢
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 2011-07-02
相关资源
最近更新 更多