Giter Site home page Giter Site logo

fasterxml / jackson-annotations Goto Github PK

View Code? Open in Web Editor NEW
1.0K 71.0 331.0 2.98 MB

Core annotations (annotations that only depend on jackson-core) for Jackson data processor

Home Page: https://github.com/FasterXML/jackson

License: Apache License 2.0

Java 96.82% Logos 3.18%

jackson-annotations's Introduction

Overview

This project contains general purpose annotations for Jackson Data Processor, used on value and handler types. The only annotations not included are ones that require dependency to the Databind package. Note that only annotations themselves (and related value classes) are included, but no functionality that uses annotations.

Project contains versions 2.0 and above: source code for earlier (1.x) versions is available from Jackson-1 repository.

Full Listing of Jackson Annotations details all available annotations; Project Wiki gives more details.

Project is licensed under Apache License 2.0.

Build (github) Maven Central Javadoc Tidelift OpenSSF  Scorecard


Usage, general

Improvements over typical Java annotations

In addition to regular usage (see below), there are couple of noteworthy improvements Jackson does:

  • Mix-in annotations allow associating annotations on third-party classes ''without modifying classes''.
  • Jackson annotations support full inheritance: meaning that you can ''override annotation definitions'', and not just class annotations but also method/field annotations!

Maven, Java package

All annotations are in Java package com.fasterxml.jackson.annotation. To use annotations, you need to use Maven dependency:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>${jackson-annotations-version}</version>
</dependency>

or download jars from Maven repository (or via quick links on Wiki)

Usage, simple

Let's start with simple use cases: renaming or ignoring properties, and modifying types that are used.

Note: while examples only show field properties, same annotations would work with method (getter/setter) properties.

Annotations for renaming properties

One of most common tasks is to change JSON name used for a property: for example:

public class Name {
  @JsonProperty("firstName")
  public String _first_name;
}

would result in JSON like:

{ "firstName" : "Bob" }

instead of

{ "_first_name" : "Bob" }

Annotations for Ignoring properties

Sometimes POJOs contain properties that you do not want to write out, so you can do:

public class Value {
  public int value;
  @JsonIgnore public int internalValue;
}

and get JSON like:

{ "value" : 42 }

or, you may get properties in JSON that you just want to skip: if so, you can use:

@JsonIgnoreProperties({ "extra", "uselessValue" })
public class Value {
  public int value;
}

which would be able to handle JSON like:

{ "value" : 42, "extra" : "fluffy", "uselessValue" : -13 }

Finally, you may even want to just ignore any "extra" properties from JSON (ones for which there is no counterpart in POJO). This can be done by adding:

@JsonIgnoreProperties(ignoreUnknown=true)
public class PojoWithAny {
  public int value;
}

Annotations for choosing more/less specific types

Sometimes the type Jackson uses when reading or writing a property is not quite what you want:

  • When reading (deserializing), declared type may be a general type, but you know which exact implementation type to use
  • When writing (serializing), Jackson will by default use the specific runtime type; but you may not want to include all information from that type but rather just contents of its supertype.

These cases can be handled by following annotations:

public class ValueContainer {
  // although nominal type is 'Value', we want to read JSON as 'ValueImpl'
  @JsonDeserialize(as=ValueImpl.class)
  public Value value;

  // although runtime type may be 'AdvancedType', we really want to serialize
  // as 'BasicType'; two ways to do this:
  @JsonSerialize(as=BasicType.class)
  // or could also use: @JsonSerialize(typing=Typing.STATIC)
  public BasicType another;
}

Usage, intermediate

Using constructors or factory methods

By default, Jackson tries to use the "default" constructor (one that takes no arguments), when creating value instances. But you can also choose to use another constructor, or a static factory method to create instance. To do this, you will need to use annotation @JsonCreator, and possibly @JsonProperty annotations to bind names to arguments:

public class CtorPOJO {
   private final int _x, _y;

   @JsonCreator
   public CtorPOJO(@JsonProperty("x") int x, @JsonProperty("y") int y) {
      _x = x;
      _y = y;
   }
}

@JsonCreator can be used similarly for static factory methods. But there is also an alternative usage, which is so-called "delegating" creator:

public class DelegatingPOJO {
   private final int _x, _y;

   @JsonCreator
   public DelegatingPOJO(Map<String,Object> delegate) {
      _x = (Integer) delegate.get("x");
      _y = (Integer) delegate.get("y");
   }
}

the difference being that the creator method can only take one argument, and that argument must NOT have @JsonProperty annotation.

Handling polymorphic types

If you need to read and write values of Objects where there are multiple possible subtypes (i.e. ones that exhibit polymorphism), you may need to enable inclusion of type information. This is needed so that Jackson can read back correct Object type when deserializing (reading JSON into Objects). This can be done by adding @JsonTypeInfo annotation on ''base class'':

@JsonTypeInfo(use=Id.MINIMAL_CLASS, include=As.PROPERTY, property="type") // Include Java class simple-name as JSON property "type"
@JsonSubTypes({@Type(Car.class), @Type(Aeroplane.class)}) // Required for deserialization only  
public abstract class Vehicle {
}
public class Car extends Vehicle {
  public String licensePlate;
}
public class Aeroplane extends Vehicle {
  public int wingSpan;
}

public class PojoWithTypedObjects {
  public List<Vehicle> items;
}

which gives serialized JSON like:

{ "items": [
  { "type": "Car", "licensePlate": "X12345" },
  { "type": "Aeroplane", "wingSpan": 13 }
]}

Alternatively, @JsonTypeInfo(use=DEDUCTION) can be used to avoid requiring the 'type' field. For deserialization, types are deduced based on the fields available. Exceptions will be raised if subtypes do not have a distinct signature of fieldnames or JSON does not resolve to single known signature.

Note that @JsonTypeInfo has lots of configuration possibilities: for more information check out Intro to polymorphic type handling

Changing property auto-detection

The default Jackson property detection rules will find:

  • All ''public'' fields
  • All ''public'' getters ('getXxx()' methods)
  • All setters ('setXxx(value)' methods), ''regardless of visibility'')

But if this does not work, you can change visibility levels by using annotation @JsonAutoDetect. If you wanted, for example, to auto-detect ALL fields (similar to how packages like GSON work), you could do:

@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY)
public class POJOWithFields {
  private int value;
}

or, to disable auto-detection of fields altogether:

@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.NONE)
public class POJOWithNoFields {
  // will NOT be included, unless there is access 'getValue()'
  public int value;
}

Support

Community support

Jackson components are supported by the Jackson community through mailing lists, Gitter forum, Github issues. See Participation, Contributing for full details.

Enterprise support

Available as part of the Tidelift Subscription.

The maintainers of jackson-annotations and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.


Further reading

Project-specific documentation:

Backwards compatibility:

Related:

  • Databinding module has more documentation, since it is the main user of annotations.

jackson-annotations's People

Contributors

aakoch avatar alexbirkett avatar ancane avatar anusien avatar arturdryomov avatar braisgabin avatar christophercurrie avatar cowtowncoder avatar dependabot[bot] avatar dili91 avatar hassaan avatar janderssonse avatar johnjohndoe avatar joohyukkim avatar joxertmd avatar kelubhai avatar kennysoft avatar lokeshn avatar marcwrobel avatar pards avatar philzen avatar pjfanning avatar reftel avatar simonetripodi avatar siwach16 avatar sp4ce avatar splatch avatar tatu-at-datastax avatar tatu-at-salesforce avatar unquietcode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jackson-annotations's Issues

Add a "three-state" boolean value, `OptBoolean`, to allow "yes/no/dont-care" choices

One of design flaws of Java annotations is the lack of null (or "missing") values.
While it is possible to specify default values for annotation properties, there is no way to distinguish between explicit settings, and defaults; and by extension, impossible to override an explicit choice.
This is most problematic with multi-property annotations, where one may want to only set a subset of properties to explicit values.

To address this problem, let's introduce a new enum, OptBoolean, to allow "optional boolean" values.

Jackson-annotations 2.3.1?

Shouldn't there be a new version of Jackson-annotations to keep the versions in line with Jackson-core?

Null value handling with @JsonSerializer

It looks like a custom @JsonSerializer will never be used with null values even if @JsonInclude(Include.ALWAYS) is used. I guess the null handling is at the ObjectMapper level but it would be nice to provide custom null handling at field/getter level. Maybe a @JsonNullSerializer or another parameter on @JsonSerializer?

'Bundled' @JsonView annotations should merge

I have created two annotation bundles:

...
@JsonView(view1.class)
@JacksonAnnotationsInside
...
public @interface bundle1 {
...

and

...
@JsonView(view2.class)
@JacksonAnnotationsInside
...
public @interface bundle2 {
...

Then I apply the annotations to properties, like this:

@bundle1
String prop1

@bundle2
int prop2

@bundle1
@bundle2
boolean prop3

I would like it if the @JSONVIEW annotations be merged for prop3 (becoming the equivalent of @JSONVIEW({view1.class, view2.class})). Right now it appears that one of the them overwrites the other one.

Alternatively, if there is another way of doing what I am trying, I would appreciate that. I know I could create a 3rd annotation named bundle1and2, but that is a bit ugly and I end up with duplicate code. I know I can also remove the @JSONVIEW from the bundles and separate it out and use @JSONVIEW({view1.class, view2.class}), but I don't want to do that either as I would prefer the views to be encapsulated in the bundles.

isGetter not showing up

Hi,

I have autodetect off for everything except for field visibility. I want to expose an isGetter which is not retrieving a field but is derived from other fields. Obviously, it is not autodetecting that particular getter because I have it off.

I added @JsonProperty and @JsonGetter above the isGetter, expecting to see it in my json object, but I still don't see it.

Any ideas? Thanks!

Force root wrapping per class

I'm working on mapping an external service that sends postbacks in wrapped JSON. I have set the @JsonRootName on the class and can read objects with a specially-configured mapper, but this wrapping behavior belongs to this service (i.e., a certain set of classes) specifically, and not to the overall system (Spring MVC, which expects a single mapping configuration).

Since it's known that this class will always need to be unwrapped, and request classes wrapped, it would be much clearer to be able to force root wrapping per class, perhaps with an alwaysWrap field on the @JsonRootName annotation. Is this a feasible feature?

Add new properties for `@JsonIgnoreProperties`, "allowGetters", "allowSetters"

(note: to support FasterXML/jackson-databind#95)

Currently @JsonIgnoreProperties affects both serialization and deserialization, and it is not possible to support a relatively common use-case of "read-only" properties; ones that are output when serializing, but that are to be ignored upon deserialization (not requiring a setter).
One way to allow this is to add a new property, enabling of which will NOT ignore named properties during serialization.

Note that adding matching "allowSetters" is easy as well, so let's add that since the reverse use case seems plausible as well.

Please move to a consistent release scheme

The current way of releasing modules individually has severe drawbacks:

Releasing all of them with a consistent version number implies the same version number for compatible artifacts. Hence, user code will use a single version number (e.g. in a Maven property) to use to refer to individual artifacts.

Now I check Maven Central and see there's a 2.3.4 of Jackson Databind and according to the Website Jackson in its core consists of Databind, Annotations and Streaming. So I upgrade my property from 2.3.3 to 2.3.4 and all of a sudden see all my projects fail to build as there's no artifact jackson-annotations in 2.3.4.

So please, if you use the same version number for a set of projects with the same group ID, please make sure they're a consistent set and don't add or drop artifacts from that set, esp. in bugfix releases. This is a PITA for uses that now have to manually skim through poms to allocate matching versions.

E.g. the pom of jackson-databind in 2.3.4 points to jackson-annotations 2.3.0. Shouldn't it point to 2.3.3 (if that was the latest version available at the release in Databind 2.3.4)?

My core point is: please consider releasing consistent sets of artifacts, even if that means that you effectively re-release an artifact with no changes. Everything but that really makes it hard for users to upgrade to new versions. Especially bugfix releases shouldn't come with surprises like these.

Make it possible to use @JsonView on method parameters

In order to continue the recent improvements we have done in Spring's Jackson integration, we would like to add support for @JsonView deserialization on request bodies as described in this issue.

The issue we have is that @JsonView only targets ElementType.METHOD and ElementType.FIELD. Would you consider adding ElementType.PARAMETER in order to allow us to support this kind of use case?

@RequestMapping(value = "/persons", consumes = APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public ResponseEntity<Person> savePerson(@JsonView(View.Summary.class) @RequestBody Person p)
{
    return new ResponseEntity<>(personRepository.save(p), HttpStatus.OK);
}

@JsonView on generic types doesn't work

I have a class defined as

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = MyEvent.class, name = "myevent"),
})
public abstract class Event
{
private D data;
...
}

My event is defined as
public class MyEvent extends Event
{

}

And User is defined as

public class User
{
@JSONVIEW({ Views.Meta.class })
private final String username;

private final String first;

private final String last;
}

However, in my JaxRS web service the username is still getting serialized out when inside the MyEvent class, but on its won (standalone User) it excludes the serialization of the username.

SimpleFilterProvider.addFilter()

I'm having issues with this method in Jackson 2.3. Here is my piece of code, taken directly from the Wiki docs:

FilterProvider filters = new SimpleFilterProvider().addFilter("test", SimpleBeanPropertyFilter.filterOutAllExcept("name"));

But for some reason, Eclipse (Kepler version) keeps displaying this error:
The method addFilter(String, BeanPropertyFilter) in the type SimpleFilterProvider is not applicable for the arguments (String, SimpleBeanPropertyFilter)

It keeps reverting back to the deprecated method even though I'm passing a SimpleBeanPropertyFilter as an argument. I've even looked in SimpleFilterProvider.class and I've found the method I'm trying to use:

/**
* Overloaded variant just to resolve "ties" when using {@link SimpleBeanPropertyFilter}.
*/
public SimpleFilterProvider addFilter(String id, SimpleBeanPropertyFilter filter) {
    _filtersById.put(id, filter);
    return this;
}

Is this a problem with my IDE, or with the library itself?

@JsonBackReference not binding relationship

I have a relationship oneToMany (Local has many Atividades), was used @JsonBackReference and @JsonManagedReference to break cyclic references, but @JsonBackReference doesn't return Local relationship in atividade model,but reverse works fine, is a bug ? or i forgot something?

Local Model

package app.model;

import com.fasterxml.jackson.annotation.*;

import org.springframework.data.jpa.domain.AbstractPersistable;

import javax.persistence.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jorge on 26/04/15.
 */
@Entity
@Table(name = "local")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Local extends AbstractPersistable<Long>{

    @Column(name = "cnpj")
    private  String cnpj;

    @Column(name = "nome")
    private  String nome;

    @Column(name = "tel")
    private  String tel;

    @Column(name = "rua")
    private  String rua;

    @Column(name = "bairro")
    private  String bairro;

    @Column(name = "cidade")
    private  String cidade;

    @Column(name = "estado")
    private  String estado;

    @Column(name = "descricao")
    private  String descricao;

    @Column(name = "capacidade_lotacao")
    @JsonProperty("capacidade_lotacao")
    private  Long capacidade_lotacao;

    @OneToMany(mappedBy = "local", targetEntity = Atividade.class,cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JsonManagedReference
    private  List<Atividade> atividades;

    public Local() {
    }

    public Local(Long id) {
        this.setId(id);
    }

    public Local( String cnpj, String nome, String tel, String rua, String bairro, String cidade, String estado, String descricao, Long capacidade_lotacao) {
        this.cnpj = cnpj;
        this.nome = nome;
        this.tel = tel;
        this.rua = rua;
        this.bairro = bairro;
        this.cidade = cidade;
        this.estado = estado;
        this.descricao = descricao;
        this.capacidade_lotacao = capacidade_lotacao;
    }

    public Local( String cnpj, String nome, String tel, String rua, String bairro, String cidade, String estado, String descricao, Long capacidade_lotacao, List<Atividade> atividades) {
        this.cnpj = cnpj;
        this.nome = nome;
        this.tel = tel;
        this.rua = rua;
        this.bairro = bairro;
        this.cidade = cidade;
        this.estado = estado;
        this.descricao = descricao;
        this.capacidade_lotacao = capacidade_lotacao;
        this.atividades = atividades;
    }

    public String getCnpj() {
        return cnpj;
    }

    public void setCnpj(String cnpj) {
        this.cnpj = cnpj;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getRua() {
        return rua;
    }

    public void setRua(String rua) {
        this.rua = rua;
    }

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }


    public Long getCapacidade_lotacao() {
        return capacidade_lotacao;
    }

    public void setCapacidade_lotacao(Long capacidade_lotacao) {
        this.capacidade_lotacao = capacidade_lotacao;
    }

    public List<Atividade> getAtividades() {

        if(atividades == null){
            atividades = new ArrayList<Atividade>();
        }
        return atividades;
    }

    public void setAtividades(List<Atividade> atividades) {
        this.atividades = atividades;
    }
}

Atividade model

package app.model;

import com.fasterxml.jackson.annotation.*;
import org.springframework.data.jpa.domain.AbstractPersistable;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jorge on 26/04/15.
 */
@Entity
@Table(name = "atividade")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Atividade extends AbstractPersistable<Long>{

    @Column(name = "nome")
    private String nome;

    @Column(name = "descricao")
    private String descricao;

    @Column(name = "tipo")
    private Long tipo;

    @Column(name = "prerequisito")
    private String prerequisito;

    @Column(name = "data")
    @Temporal(TemporalType.DATE)
    private Date data;

    @Column(name = "hora_inicio")
    @Temporal(TemporalType.TIME)
    private Date hora_inicio;

    @Column(name = "hora_fim")
    @Temporal(TemporalType.TIME)
    private Date hora_fim;

    @Column(name = "inscricoes_inicio")
    @Temporal(TemporalType.DATE)
    private Date inscricoes_inicio;

    @Column(name = "inscricoes_fim")
    @Temporal(TemporalType.DATE)
    private Date inscricoes_fim;

    @Column(name = "valor_investimento")
    private BigDecimal valor_investimento;

    @Column(name = "valor_desconto")
    private BigDecimal valor_desconto;

    @ManyToOne
    @JoinColumn(name = "local_id")
    @JsonBackReference
    private Local local;

    @ManyToMany
    @JoinTable(name = "palestrante_atividade",
    joinColumns = {
            @JoinColumn(name = "id_atividade")
    },inverseJoinColumns = {
            @JoinColumn(name = "id_palestrante")
    })
    private List<Palestrante> palestrantes = new ArrayList<Palestrante>();

    public Atividade() {
    }

    public Atividade(String nome, String descricao, Long tipo, String prerequisito, Date data, Date hora_inicio, Date hora_fim, Date inscricoes_inicio, Date inscricoes_fim, BigDecimal valor_investimento, BigDecimal valor_desconto) {
        this.nome = nome;
        this.descricao = descricao;
        this.tipo = tipo;
        this.prerequisito = prerequisito;
        this.data = data;
        this.hora_inicio = hora_inicio;
        this.hora_fim = hora_fim;
        this.inscricoes_inicio = inscricoes_inicio;
        this.inscricoes_fim = inscricoes_fim;
        this.valor_investimento = valor_investimento;
        this.valor_desconto = valor_desconto;
    }

    public Atividade(String nome, String descricao, Long tipo, String prerequisito, Date data, Date hora_inicio, Date hora_fim, Date inscricoes_inicio, Date inscricoes_fim, BigDecimal valor_investimento, BigDecimal valor_desconto, Local local, ArrayList<Palestrante> palestrantes) {
        this.nome = nome;
        this.descricao = descricao;
        this.tipo = tipo;
        this.prerequisito = prerequisito;
        this.data = data;
        this.hora_inicio = hora_inicio;
        this.hora_fim = hora_fim;
        this.inscricoes_inicio = inscricoes_inicio;
        this.inscricoes_fim = inscricoes_fim;
        this.valor_investimento = valor_investimento;
        this.valor_desconto = valor_desconto;
        this.local = local;
        this.palestrantes = palestrantes;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Long getTipo() {
        return tipo;
    }

    public void setTipo(Long tipo) {
        this.tipo = tipo;
    }

    public String getPrerequisito() {
        return prerequisito;
    }

    public void setPrerequisito(String prerequisito) {
        this.prerequisito = prerequisito;
    }

    public Date getData() {
        return data;
    }

    public void setData(Date data) {
        this.data = data;
    }

    public Date getHora_inicio() {
        return hora_inicio;
    }

    public void setHora_inicio(Date hora_inicio) {
        this.hora_inicio = hora_inicio;
    }

    public Date getHora_fim() {
        return hora_fim;
    }

    public void setHora_fim(Date hora_fim) {
        this.hora_fim = hora_fim;
    }

    public Date getInscricoes_inicio() {
        return inscricoes_inicio;
    }

    public void setInscricoes_inicio(Date inscricoes_inicio) {
        this.inscricoes_inicio = inscricoes_inicio;
    }

    public Date getInscricoes_fim() {
        return inscricoes_fim;
    }

    public void setInscricoes_fim(Date inscricoes_fim) {
        this.inscricoes_fim = inscricoes_fim;
    }

    public BigDecimal getValor_investimento() {
        return valor_investimento;
    }

    public void setValor_investimento(BigDecimal valor_investimento) {
        this.valor_investimento = valor_investimento;
    }

    public BigDecimal getValor_desconto() {
        return valor_desconto;
    }

    public void setValor_desconto(BigDecimal desconto_aluno) {
        this.valor_desconto = desconto_aluno;
    }
    public Local getLocal() {
        return local;
    }

    public void setLocal(Local local) {
        this.local = local;
    }

    public List<Palestrante> getPalestrantes() {
        return palestrantes;
    }

    public void setPalestrantes(ArrayList<Palestrante> palestrantes) {
        this.palestrantes = palestrantes;
    }
}

Broken link on home page

On the home page for the jackson-annotations project, this link is broken:
"Full Listing of Jackson Annotations"

Add @JsonWrapped (to complement @JsonUnwrapped)

Re-rasing this issue from the old Jira bug tracker: https://jira.codehaus.org/browse/JACKSON-781

It was suggested this should be raised in the data bind project, but as it is an annotation, this seemed a better fit.

This is the original issue description:

@JsonUnwrapped allows people who want a more compressed JSON hierarchy than their POJO to affect the process, but there is no option for the reverse. I have a REST service producing unnecessary additional layers of abstraction that i would like to exclude from my Java POJOs rather than writing all sorts of unseemly wrapper classes.

I agree this would be a great feature to avoid unnecessary wrappers on the Java side when consuming JSON APIs.

I'd picture a new annotation that would take a form along the lines of:

@JsonWrapped("address")
@JsonProperty("house_number")
private String houseNumber;

or it could be an additional parameter of the @JsonProperty annotation:

@JsonProperty(value="house_number", wrapped="address")
private String houseNumber;

or, possibly, the value parameter of the @JsonProperty annotation could specify the object hierarchy:

@JsonProperty("address.house_number")
private String houseNumber;

This may introduce backwards compatibility issues, though, as it would mean this behaved differently than it currently does.

It would be good if it could also unwrap multiple levels, such as:

@JsonWrapped("contact_details.address")
@JsonProperty("house_number")
private String houseNumber;

Though, this would mean the value of the @JsonWrapped annotation was parsed differently than the value of the @JsonProperty annotation (as "contact_details.address" in the @JsonProperty annotation would refer to an object key named "contact_details.address").

@JsonIgnore dont work for collections like set,map,list via Mix-in annotations

I tried to create an interface that will used as mix-in annotations for jackson.

the annotation @JsonIgnore works for types like String,int,CustomObject but it doesn't work for Collections like Set, List, Map I still get the Collection as part of my JSON output.

I put the @JsonIgnore only on the getter that return the Collection for example:

@JsonIgnore
Set getCustomObjects();

I am trying to parse JAXB class so I define the serilizers like this:

objectMapper.setAnnotationIntrospector(AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(), new JaxbAnnotationIntrospector()));

objectMapper.addMixInAnnotations(MainObject.class, MainObjectMixInAnnotations.class);

any idea?

@JsonRootName Not Working for Collection Type

The following is the test case.


POJO Classs

@JsonRootName("Employee")
public class Employee implements Serializable {
private String empName;
private String empNo;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpNo() {
return empNo;
}
public void setEmpNo(String empNo) {
this.empNo = empNo;
}
}


TEST CASE

public class EmployeeTest {
@test
public void testEMPJsonData() throws Exception{

    Employee emp =new Employee();
    emp.setEmpName("john");
    emp.setEmpNo("1234");
    emp.setPermentAddress("india");
    List<Employee> empList = new ArrayList<Employee>();
    empList.add(emp);
    /********** - JACKSON *******************/
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    mapper.setAnnotationIntrospector(new AnnotationIntrospectorPair(new  JacksonAnnotationIntrospector(), new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())));
    mapper.writeValue(System.out, empList); 

}

}


ouput

{"ArrayList":[{"empName":"john","empNo":"1234"}]}

Expected : {"Employee":[{"empName":"john","empNo":"1234"}]}

why it behaving like this for collections?

Add `@JsonTypeInfo.skipWritingDefault`

(note: related to FasterXML/jackson-databind#644)

It should be possible to indicate via annotation that the type id writing may be skipped, if the type is the same as indicated by @JsonProperty.defaultImpl.
Note that type id writer may have some limitations regarding when suppression is possible (and/or how); so this annotation is more of a suggestion, and it should not be assumed that type id will absolutely not be written. Rather, it can be seen as an optimization for reducing writing of unnecessary type ids.

Add `maySerializeAsObject()` and `maySerializeAsObject()` in `ObjectIdGenerator` to support JSOG

(note: related to FasterXML/jackson-databind#622)

Since there are potential drawbacks/ambiguities to handling (JSON) Object serialized object ids (since basically it makes it impossible to reliably know object definition and reference from each other, without considering actual Object contents -- something that scalar ids allow), let's require ObjectIdGenerators for object-value object ids to implement a new method.

Why @JsonProperty annotation can be ignored?

I use annotation with "crnId" field in a class like this:

@JsonProperty("internalid")
private Long crmId;

But I see
{"action":"updateCustomer","data":{"firstname":"au043","lastname":"au043","email":"[email protected]"},"crmId":186}
after serialization in JSON string.
It seems that annotation has been ignored.
How it can be fixed?

Duplicate property when serializing polymorphic object.

Given the following code....

package scratch;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(  
    use = JsonTypeInfo.Id.NAME,  
    include = JsonTypeInfo.As.PROPERTY,  
    property = "mime", visible = true)
@JsonSubTypes({    
    @Type(value = MovieFile.class, name = "video/ogg"),
    @Type(value = ImageFile.class, name = "image/jpeg")
})
public abstract class MyFile {
    private String mime;
    private String name;

    public String getMime() {
        return mime;
    }

    public void setMime(String mime) {
        this.mime = mime;
    }

    public String getName() {
        return name;
    }

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

}

package scratch;

public class ImageFile extends MyFile{
    private Long width;
    private Long height;

    public Long getWidth() {
        return width;
    }

    public void setWidth(Long width) {
        this.width = width;
    }

    public Long getHeight() {
        return height;
    }

    public void setHeight(Long height) {
        this.height = height;
    }

}

package scratch;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayOutputStream;
import org.junit.Test;

public class MyFileTests {

    private final ObjectMapper mapper = new ObjectMapper();

    @Test
    public void test() throws Exception {

        ImageFile imageFile = new ImageFile();
        imageFile.setMime("image/jpeg");
        imageFile.setName("image.jpg");
        imageFile.setWidth(100L);
        imageFile.setHeight(100L);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        mapper.writeValue(baos, imageFile);

        System.out.println(baos.toString());


    }

}

I get the following json printed..

{"mime":"image/jpeg","mime":"image/jpeg","name":"image.jpg","width":100,"height":100}

Is there any way to stop the duplicate mime property of the serialized object?

Add @Documented to @JsonPropertyDescription - Feature request

Hi,

we are planning on using @JsonPropertyDescription to carry additional description into our generated schemas. Currently this annotation is not annotated with @<a href=http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Documented.html">Documented so the content is not visible in JavaDoc. We are currently using our custom one to come over this but I think this would be generally usefull to have (i.e. not duplicating comments). What do you think?
Regards,
Zoltan

how ignore property of property?

i have a [personel] model like this
that have [location] property
i want to ignore [parent] property in Location
just for this use not for all time
i want to ignore [parent] property in location just in Personel model

is annotation like @ignoreproperty("perent") in property level not in class level

public class Personel extends BaseEntity  {
    private Location location;

    public Location getLocation() {
        return location;
    }
    public void setLocation(Location location) {
        this.location = location;
    }
}

public class Location extends BaseEntity{
    private String code;
    private String name;
    private Location parent;

    public Location getParent() {
        return parent;
    }

    public void setParent(Location parent) {
        this.parent = parent;
    }
}

Add an annotation to indicate 'always use id'

Current behavior for Object Id serialization is to serialize first instance normally, and then serialize all the other references as ids.
This makes sense when data must be self-contained, i.e. fully deserializable without any external information.

However, there are cases where it would make sense to serialize ALL instances as just id; this makes sense if deserialization side knows how to map these ids externally to instances, without requiring them to be included in serialization.

@JsonUnwrapped conflicts with @JsonAnySetter/@JsonAnyGetter

I have this class:

@RooJavaBean(settersByDefault = false)
@JsonPropertyOrder({"txid", "vout"})
public class TransactionOutputRef extends BaseClass {

    @JsonProperty("txid")
    private String txId;

    @JsonProperty("vout")
    private Integer vout;

    /**
     * Full constructor.
     * 
     * @param txId - transaction id.
     * @param vout - output number.
     */
    public TransactionOutputRef(@JsonProperty("txid") String txId, @JsonProperty("vout") Integer vout) {
        this.txId = txId;
        this.vout = vout;
    }


}

Which is used as an @JsonUnwrapped property in this class:

@RooJavaBean(settersByDefault = false)
public class ListUnspentResult extends JsonExtra {

    @JsonUnwrapped
    private TransactionOutputRef txRef;

    private String scriptPubKey;
    private BigDecimal amount;
    private Integer confirmations;

    private Map<String, Object> otherFields = newHashMap();

    /**
     * Sets name and value of other (unknown) JSON fields.
     * 
     * @param field
     * @param value
     */
    @JsonAnySetter
    public void set(String field, Object value)  {
        otherFields.put(field, value);
    }


    /**
     * Gets names and values of all other (unknown) JSON fields.
     * 
     * @return Names of other fields available. 
     */
    @JsonAnyGetter
    public Map<String, Object> getOtherFields() {
        return Collections.unmodifiableMap(otherFields);
    }

}

As you can see the class also has @JsonAnyGetter and @JsonAnySetter methods to collect other fields.

Now, if i deserialize this:

{"txid":"280acc1c3611fee83331465c715b0da2d10b65733a688ee2273fdcc7581f149b","vout":0,"scriptPubKey":"76a91426ab1c83e2a8269b7007baf0244151cca4c5e3fd88ac","amount":5.00000000,"confirmations":956}

I get an ListUnspentResult object, where txid and vout are stored in both the txRef property annotated with @JsonUnwrapped AND in the otherFields map, and when I serialize it back to json, I get this:

{"txid":"280acc1c3611fee83331465c715b0da2d10b65733a688ee2273fdcc7581f149b","vout":0,"scriptPubKey":"76a91426ab1c83e2a8269b7007baf0244151cca4c5e3fd88ac","amount":5.00000000,"confirmations":956,"vout":0,"txid":"280acc1c3611fee83331465c715b0da2d10b65733a688ee2273fdcc7581f149b"}

where txid and vout (the properties of TransactionOutputRef ) are included twice.

Annotations not working on single object but working fine on list<> of objects (on Glassfish4)

jackson-annotations-2.2.3.jar
=============== WORKING =====================
c:>curl -H "Accept:application/json" http://localhost:8080/emberGF4/rest/customers
{"customers":[{"id":1,"first_name":"F1","last_name":"L1","order_ids":[1]},{"id":2,"first_name":"F2","last_name":"L2","order_ids":[]}]}

produced by:
@get
@produces(MediaType.APPLICATION_JSON)
public Customers get(@QueryParam("ids[]") List ids) {
if (ids != null && !ids.isEmpty()) {
return new Customers(manager.findByIds(ids));
}
return new Customers(manager.findAll());
}

@JsonRootName("customers")
class Customers extends ArrayList<Customer> {
    private static final long serialVersionUID = 1L;

    public Customers(Collection<? extends Customer> c) {
        addAll(c);
    }
}

=============== NOT WORKING =====================
c:>curl -H "Accept:application/json" http://localhost:8080/emberGF4/rest/customers/2
{"firstName":"F2","id":2,"lastName":"L2","orders":[]}

On single object the @JsonRootName("customer") is missing and @JsonIdentityReference(alwaysAsId = true) @JsonProperty("order_ids")

produced by:
@path("/{id}")
@get
@produces(MediaType.APPLICATION_JSON)
public Customer get(@PathParam("id") Long id) {
Customer c = manager.find(id);
return c;
}

================= Customer =========================
package ember.sample.entity;

import java.util.Set;
import java.util.TreeSet;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@entity
@table
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonRootName("customer")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(length = 24)
@Size(max = 24)
@NotEmpty
@JsonProperty("first_name")
private String firstName;

@Column(length = 24)
@Size(max = 24)
@NotEmpty
@JsonProperty("last_name")
private String lastName;

@OneToMany(mappedBy = "customer")
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty("order_ids")
private Set<CustomerOrder> orders = new TreeSet<>();

public Customer() {
}

public Customer(Long id) {
    super();
    this.id = id;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Set<CustomerOrder> getOrders() {
    return orders;
}

public void setOrders(Set<CustomerOrder> orders) {
    this.orders = orders;
}

}

Add new Type Id type, EXISTING_PROPERTY

(note: addition needed to implement FasterXML/jackson-databind#250 for databind)


It would make sense to add one new value for JsonTypeInfo.As enumeration: EXISTING_PROPERTY. Its semantics would be similar to PROPERTY on deserialization; but on serialization, it would be assumed that standard property serialization is used, and so TypeSerializer can be a no-operation.

@jsonignore annotation by way of mixin only working on field, but not get/set methods for jaxb generated classes

See: http://markmail.org/message/4x2lj6fgikrv4vb4

I have a simple xml schema

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
    targetNamespace="http://xmlns.test.com/test" xmlns:test="http://xmlns.test.com/test">

    <xs:element name="Pod">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="username" type="xs:string"/>
                <xs:element name="password" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

that I invoke the xjc tool to generate the following class:

package com.test.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "username",
    "password"
})
@XmlRootElement(name = "Pod")
public class Pod {

    @XmlElement(required = true)
    protected String username;
    @XmlElement(required = true)
    protected String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String value) {
        this.username = value;
    }
    public String getPassword() {
        return password;
    }

    public void setPassword(String value) {
        this.password = value;
    }

}

I'm trying to utilize the mixin functionality to prevent the getPassword method from serializing by way of an @JsonIgnore.

http://fasterxml.github.com/jackson-annotations/javadoc/2.0.6/com/fasterxml/jackson/annotation/JsonIgnore.html

I have found that the mixin only seems to work when the @JsonIgnore property is applied on the password field,

@JsonIgnore protected String password;

but does nothing when set on the method itself

@JsonIgnore abstract public String getPassword();

As I ultimately want to allow setPassword, but not getPassword, it does not make sense to put the @JsonIgnore on the field.
Thus I need to get it working on the getPassword method. Reading the javadoc, I understand that I eventually will need to also utilize the @JsonProperty annotation on the setter due to change in behaviour of how @JsonIgnore works. But what I'm seeing is that @JsonIgnore is not working for anything but the field in the first place.

Any ideas what could be going on? Is this likely a bug, or have I messed up?
I'm utilizing jackson 2.0.6.

package com.test.model;

import com.fasterxml.jackson.annotation.JsonIgnore;

abstract class PodMixIn
{
  // @JsonIgnore protected String password;
  @JsonIgnore abstract public String getPassword();
  // @JsonIgnore abstract public void setPassword(String value);
}

I have uploaded a fully self-contained test case that demonstrates the issue at:
https://docs.google.com/open?id=0Bxy6NL7ud-h6Wjg3MTl5WF9rbUk

Root name of JSON data format

This is Person.java

@JsonRootName("Person")
public class Person {
    private String name;
    private double height;
    private int age;
    @JsonSerialize(using=CustomDateSerializer.class)
    private Date date;
    @JsonProperty("Address")
    private Address address;
        //normal constructor
        //getters/setters
}

This is my main class:

public class AppJson {
    public static void main(String[] arg) throws JsonGenerationException,
            JsonMappingException, IOException {
        Address a = new Address("Jln Koli", "90121", "Vila", "Belgium");
        Person p = new Person("Ali Bin Baba", new Date(), 90.0, 12, a);

        Json json = new Json(p);
        System.out.println(json.toString());
    }
}

Output:

{
  "name" : "Ali Bin Baba",
  "age" : 12,
  "date" : "06-12-2014",
  "Address" : {
    "postcode" : "90121",
    "city" : "Vila",
    "state" : "Belgium",
    "street" : "Jln Koli"
  }
}

But, the output I want is like this:

{
  "Person": {
    "name": "Ali Bin Baba",
    "age": "12",
    "date": "06-12-2014",
    "Address": {
      "postcode": "90121",
      "city": "Vila",
      "state": "Belgium",
      "street": "Jln Koli"
    }
  }
}

My dependencies:

<dependencies>
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.3</version>
  </dependency>
</dependencies>

Did you know, which part is wrong??

@JsonIdentityInfo Custom Generator : serializing id and ref differently ?

I am trying to create a Custom Generator based on IntSequenceGenerator, I would like to serialize id and ref differently, like so

{ "a": { "@id": 1, "name": "foo"}, b: {"$ref" : 1}},

What I am getting right now is :

{ "a": { "@id":  {"$ref" : 1}, "name": "foo"}, b: {"$ref" : 1}}

Is what I am trying to achieve feasible in Jackson ?

Extracting Mixin infrastructure to a general purpose library

hi,
I might be wrong here but I think that it might be interesting to have the mixin infrastructure as a general purpose library.
In my company we have something that adds metadata on exceptions for client communications, monitoring and BI. This works with annotations and I think adding mixin support can be interesting.
Seeing as I like this feature in Jackson I thought to try and see if you think it can be generalized.

Add `@JsonCreatore.mode` property to explicitly choose between delegating- and property-based creators

There is one potentially ambiguous case for @JsonCreator: a single-argument creator, with implicit (but not explicit) name for the argument, could conceivably be either delegating- or property-based creator. Although better heuristics might be able to choose correctly, it is likely that there are cases where no heuristic could give 100% correct result, and an explicit override is needed.
Further, extension modules may want to have a say here as well (for example, Scala module has better class metadata available), and adding a property to introspect allows overriding of introspection.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.