0

I am quite new to Spring Boot and REST API. I am trying to build a simple REST API that deals with arbitrary JSON data. I got it working to the point where I can use GET and POST.

What I would want to achieve is to send the same data back with an additional field added. If the data is this(Can be arbitrary).

{
    "firstname" : "Dheeraj",
    "lastname"  : "Dhall"
}

I would want something like this back.

{
    "id": "1"
    "firstname" : "Dheeraj",
    "lastname"  : "Dhall"
}

The method that handles PUT request has JsonNode as the parameter and my model is something like this

public class Person {
    private Long id;
    private Map<String, String> map;
}

So in the method that handles the PUT request I create a map and load data from the JSON Object. So the problem is that my response is something like this

{
    "id": "1"
    "map":{
             "firstname" : "Dheeraj",
             "lastname"  : "Dhall"
          }
}

How do I get it to print without a "map"? what is the best way to handle arbitrary JSON data?

  • You could put `"id"` into the `Map`. – chrylis -cautiouslyoptimistic- Nov 23 '19 at 02:23
  • In your `Person` class annotate `Map map` getter with `@JsonAnyGetter` annotation. See also: [How to use dynamic property names for a Json object](https://stackoverflow.com/questions/55684724/how-to-use-dynamic-property-names-for-a-json-object), [Dynamic change of JsonProperty name](https://stackoverflow.com/questions/55845478/dynamic-change-of-jsonproperty-name-using-jackson-java-library), [Why I'm not able to unwrap and serialize a Java map?](https://stackoverflow.com/questions/18043587/why-im-not-able-to-unwrap-and-serialize-a-java-map-using-the-jackson-java-libra) – Michał Ziober Nov 23 '19 at 08:30
  • If the data is arbitrary then there it will not work with nested JSON if the map is Map. I tried changing it to Map but hibernate throws an error stating it cannot determine the number of columns. Is there a work around this? – Dheeraj Dhall Nov 27 '19 at 06:02

1 Answers1

0

Why do you need to use Map in your Person class? I think you don't need to use Map in this case, you can change your Person class like below:

public class Person {
    private Long id;
    private String firstname;
    private String lastname;
}