C
C
Crunchor2020-04-21 13:59:47
Java
Crunchor, 2020-04-21 13:59:47

How to bind JSON to POJO without parent element?

There is this JSON:

{
   "data":[
      {
         "store_id":"6217704612",
         "created":"1587466128",
         "price":"5000",
         "amount":"1"
      },
      {
         "store_id":"6217704613",
         "created":"1587466130",
         "price":"2000",
         "amount":"2"
      }
   ]
}


Mapping
@Getter
@Setter
public class MyJSON {
    @JsonProperty("data")
    private List<MyData> data;
}


@Entity
@Getter
@Setter
public class MyData {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @JsonProperty("store_id")
    private long storeId;
    private Timestamp created;
    private double price;
    private double amount;
}


Now the code works like this:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
MyJSON myJSON = mapper.readValue(jsonString, MyJSON.class);
List<MyData> myData = myJSON.getData();


In myData I get the collection I need. How can this code/mapping be rewritten to not create a MyJSON object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Kolun, 2020-04-21
@Crunkor

Try like this:

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString).path("data");
List<MyData> myJSON = mapper.readValue(node.toString(), new TypeReference<List<MyData>>() {});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question