简体   繁体   中英

Serializing and deserializing JSON targeting JAVA classes with Jackson

Trying to deserialize/serialize JSON into Java beans I've created. Really new to Jackson and this endeavor, so bear with me. I have the following:

{
  "foo": {
    "firstBlock": {
      "myValue": 1,
      "someBool": true,
      "stringValue": "OK"
    },
    "anotherBlock": {
      "values": [
        {
          "yikes01": 42
        },
        {
          "yikes02": 215
        }
      ],
      "myInt": 64,
      "logging": "Yes"
    }
  }
}

My Java beans are broken down into several as the objects in the JSON are used repeatedly, so it would be:

@JsonRootName("foo")
public class FooBean {
  private FirstBlockBean firstBlock;
  private AnotherBlockBean anotherBlock;

  @JsonGetter("firstBlock")
  public FirstBlockBean getFirstBlock() { return firstBlock; }

  @JsonSetter("firstBlock")
  public void setFirstBlock(FirstBlockBean firstBlock) { this.firstBlock = firstBlock; }

  @JsonGetter("anotherBlock")
  public AnotherBlockBean getAnotherBlock() { return anotherBlock; }

  @JsonSetter("firstBlock")
  public void setAnotherBlock(AnotherBlockBean anotherBlock) { this.anotherBlock = anotherBlock; }
}

@JsonRootName("firstBlock")
public class FirstBlockBean {

  private int myValue;
  private Boolean someBool;
  private String stringValue;

  @JsonGetter("myValue")
  public int getMyValue() { return myValue; }

  @JsonSetter("myValue")
  public void setMyValue(int myValue) { this.myValue = myValue; }

  @JsonGetter("someBool")
  public Boolean getSomeBool() { return someBool; }

  @JsonSetter("someBool")
  public void setSomeBool(Boolean someBool) { this.someBool = someBool; }

  @JsonGetter("stringValue")
  public String getStringValue() { return stringValue; }

  @JsonSetter("someBool")
  public void setStringValue(String stringValue) { this.stringValue = stringValue; }
}

...and AnotherBlockBean class implemented in similar fashion (omitted for brevity.) I'm using Jackson for this, and my question is - is there a mechanism in Jackson for serializing and deserializing for this case? Ideally I'd like something along the lines of (pseudo-code below because I've not been able to surface anything via Google searches or searches on here):

// Assume "node" contains a JsonNode for the tree and foo is an uninitialized FooBean class object.
JsonHelper.deserialize(node, FooBean.class, foo);

At this point I'd be able to read the values back:

int i = foo.getFirstBlock().getMyValue();
System.out.println("i = " + i); // i = 1

Similarly I'd like to be able to take the foo instance and serialize it back into JSON with another method. Am I dreaming for wanting this sort of built-in functionality or does it exist?

The main class when working with Jackson is the ObjectMapper. It has a lot of options, take a look at the available methods.

This is an example of a typical helper class that uses the ObjectMapper to convert between Java objects and Strings.

public class JsonHelper {

    private ObjectMapper objectMapper;

    public JsonHelper(){

        this.objectMapper = new ObjectMapper();

        // Your mapping preferences here
        this.objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
        this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        this.objectMapper.setSerializationInclusion(Include.NON_NULL);
        this.objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }

    public String serialize(Object object) {
        try {
            return this.objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            // TODO Handle exception
            return null;
        }
    }

    public <T> T deserialize(String json, Class<T> clazz) {
        try {
            return this.objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            // TODO Handle exception
            return null;
        }
    }

    public <T> T deserialize(String json, TypeReference<T> valueTypeRef) {
        try {

            return this.objectMapper.readValue(json, valueTypeRef);
        } catch (Exception e) {
            // TODO Handle exception
            return null;
        }
    }
}

Some tips:

  • If the name of the getter and setter methods follows the usual convention, you can omit the @JsonGetter and @JsonSetter annotations and just use the @JsonProperty annotation in the field declaration
  • If the name of the java field is equal to the node name in the JSON, you can also omit the @JsonProperty annotation (Jackson will map JSON nodes and Java fields with matching names).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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