Question

I have a JSON object, say:

{
  "foo": {
    "bar": 1
  },
  "baz": 2
}

and I want to bind it into a Java object, like:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
  private int bar;
  @JsonProperty("baz")
  private int baz;
}

How can I set the value of foo.bar from JSON to the bar field in the Foo Java object?

I've tried annotating the field with @JsonProperty("foo.bar"), but it doesn't work like that.

Was it helpful?

Solution

This ain't perfect but it's the most elegant way I could figure out.

@JsonProperty("foo")
public void setFoo(Map<String, Object> foo) {
  bar = (Integer) foo.get("bar");
}

OTHER TIPS

There is no automated functionality for this (as far as I know), but this is a somewhat often requested feature; there is this Jira RFE: http://jira.codehaus.org/browse/JACKSON-132 that sounds like what you are looking for.

Here a quick example that works:

JSON:

[{"function":{"name":"Function 1"}},
 {"function":{"name":"Function 2"}}]

Java:

import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Function {
    @JsonProperty("name")
    private String name;

    @JsonProperty("function")
    public void setFunction(Map<String, Object> function) {
      name = (String) function.get("name");
    }
}

That's like binding an apple to an orange! Another 'catchy phrase' would be, "Impedance Mismatch", or in Star Trek 1, "Non Sequetor!" Bind it a MATCHED object, then do new assignment in Java between the different kinds of objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top