JsonIgnore and JsonProperty not behaving as I expect

jackson

I have a simple class that I want to deserialize into JSON using Jackson. I want to rename one field logically in my JSON and the other I want to have the same name as defined in my Java class.

  @JsonSerialize(include = Inclusion.NON_NULL)
public static class Manifest {

  public Manifest(){
    this.files = new ArrayList<String>();
  }

  @JsonProperty("manifest-version")
  private String manifestVersion;

  private ArrayList<String> files; 

  @JsonIgnore
  public String getManifestVersion() {
    return manifestVersion;
  }

  @JsonIgnore
  public void setManifestVersion(String manifestVersion) {
    this.manifestVersion = manifestVersion;
  }

  public ArrayList<String> getFiles() {
    return files;
  }

  public void setFiles(ArrayList<String> files) {
    this.files = files;
  }
  public void addFile(String file) {
    this.files.add(file);
  }

}

I'm expecting the @JsonIgnore for the getter/setter to cause manifestVersion to not become a JSON property (But should create a JSON property for manifest-version, where I have the @JsonProperty defined.

Expected output is
{
"manifest-version" : "2.0"
}
Actual output is
{
"manifest-version" : "2.0",
"manifestVersion":"2.0"
}

Any help would be appreciated.

Best Answer

I tried executing your code with Jackson 2.2 and i'm getting the expected output

import java.util.ArrayList;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion;

public class Test {

  @JsonSerialize(include = Inclusion.NON_NULL)
  public static class Manifest {

    public Manifest(){
      this.files = new ArrayList<String>();
    }

    @JsonProperty("manifest-version")
    private String manifestVersion;

    private ArrayList<String> files; 

    @JsonIgnore
    public String getManifestVersion() {
      return manifestVersion;
    }

    @JsonIgnore
    public void setManifestVersion(String manifestVersion) {
      this.manifestVersion = manifestVersion;
    }

    public ArrayList<String> getFiles() {
      return files;
    }

    public void setFiles(ArrayList<String> files) {
      this.files = files;
    }
    public void addFile(String file) {
      this.files.add(file);
    }

  }

  public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper obj = new ObjectMapper();
        Manifest m = new Manifest();
        m.setManifestVersion("2.0");
        System.out.println(obj.writeValueAsString(m));      
    }
}

Output: {"files":[],"manifest-version":"2.0"}

what version of jackson are you using?

Related Topic