Parse JSON in Java with intermediate element ({"realKey": {"badKey": "goodValue"}}))

69 views Asked by At

I have a problem parsing a JSON to a Java class. I have read about Elasticsearch Search App APIs, and I have found responses are like this one:

{
  "name": {"raw": "Hello world"},
  "number": {"raw": 7.5}
}

That is, every field is an object with a key called raw and the real value I want. I would like to have a Java class like this one:

public class MyClass {
  private String name;
  private Double number;
}

I haven't seen in Jackson or any other mapping library something in order to map this JSON easily.

I would expect something like that if we use Jackson (is not a requisite, we could use any other parsing library):

ObjectMapper objectMapper = new ObjectMapper();
MyClass jsonParsed = objectMapper.readValue(json, MyClass.class);
2

There are 2 answers

2
Gopinath Radhakrishnan On

You can read the JSON Property as Map and unpack the needed attribute and assign to the property. You should be able to do something like:

class MyClass {
    private String name;
    private Double number;

    @JsonProperty("name")
    private void unpackNameFromNestedRawObject(Map<String, String> name) {
      this.name = name.get("raw");
    }

    @JsonProperty("number")
    private void unpackNumberFromNestedRawObject(Map<String, Double> number) {
      this.number = number.get("raw");
    }

    public String getName() {
      return name;
    }

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

    public Double getNumber() {
      return number;
    }

    public void setNumber(final Double number) {
      this.number = number;
    }

    @Override
    public String toString() {
      return "MyClass{" + "name='" + name + '\'' + ", number=" + number + '}';
    }
  }
0
Diego Sanz On

For anyone who have the same doubt, I finally created a class like this one:

public class Wrapper<T> {
    T value;
    // getters/setters
}

And then I created my class like this one:

public class MyClass {
    RawWrapper<String> aStringField;
    RawWrapper<Integer> aIntegerField;
    ...
}

With that, JSON is parsed correctly. If then you want to transform it to another class with the same fields but without RawWrappers, in my case I have used Mapstruct to indicate how to pass from RawWrapper to String, RawWrapper to Integer, etc., and that's all!