Home > Mobile >  How to map a dynamic object with Jackson
How to map a dynamic object with Jackson

Time:02-04

Hello I have the next json response:

enter image description here

As you can see I have a resource object with many different objects inside, but these objects could be different depending on the input. I created the next pojo:

This in my input Pojo:

import java.util.List;

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

@JsonIgnoreProperties(ignoreUnknown = true)
public class Input
{

  private String filepath;
  private String inputType;
  private List<Object> resources;

  @JsonProperty("filepath")
  public String getFilepath() {
    return filepath;
  }

  public void setFilepath(final String filepath) {
    this.filepath = filepath;
  }

  @JsonProperty("input_type")
  public String getInputType() {
    return inputType;
  }

  public void setInputType(final String inputType) {
    this.inputType = inputType;
  }

  @JsonProperty("resources")
  public List<Object> getResources() {
    return resources;
  }

  public void setResources(final List<Object> resources) {
    this.resources = resources;
  }
}

I added the resources as an object List, but I can see that it is an Object with different objects inside it. How can I map this different objects to an object in Java? In fact I need to count how may resources I have, but I'm struggling trying to achieve this. Thanks!

CodePudding user response:

Use Map<String, Object> resources instead of List<Object> resources. It allows you to have a map with different objects inside.

public class Input{
  private String filepath;
  private String inputType;
  private Map<String, Object> resources;

  // getters and setters here
}
  •  Tags:  
  • Related