-1

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);
Diego Sanz
  • 36
  • 6
  • I believe this is a go-to usecase for [Josson](https://github.com/octomix/josson) - try reading a few questions about it here on SO and you'll see. – Shark Apr 06 '23 at 12:19
  • As this library doesn't have a big number of stars, I don't think it would be the best solution for a production environment. Isn't there any way to do it with Jackson ir any other popular parsing library? – Diego Sanz Apr 10 '23 at 14:20
  • For the moment, I have created a class like the indicated in this question: https://stackoverflow.com/questions/75977888/use-jackson-deserializer-to-read-child-json-object and then I map with Mapstruct from the other class to this one – Diego Sanz Apr 12 '23 at 06:29

1 Answers1

1

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 + '}';
    }
  }
  • That's also a good option, but if my class has, lest's say 35 fields, it's a little bit annoying to create 35 functions like that example. – Diego Sanz Apr 20 '23 at 15:20
  • The are IDE specific custom code generation template that can used to used for generating boilerplate code. For example https://stackoverflow.com/questions/16145800/generate-custom-java-getters-and-setters – Gopinath Radhakrishnan Apr 21 '23 at 05:14