Home > database >  How to convert a JSON request into a list of specific format n spring?
How to convert a JSON request into a list of specific format n spring?

Time:02-04

I have a request JSON list like this:

[
 {
  Id: 0,
  values: [a, b, c, d]
 },
 {
  Id: 1,
  values: [1, 2, 3, 4]
 },
 .
 .
 .
]

How do I convert this to a list like this:

[
 {
  Name: a,
  Count: 1
 },
 {
  Name: b,
  Count: 2
 }
 {
  Name: c,
  Count: 3
 }
 {
  Name: d,
  Count: 4
 }
]

I have a dto class consisting of name and count attributes.

CodePudding user response:

Try using a zip on the value lists to create a list of tuples containing the nth element of each.

CodePudding user response:

As far as I can see, the result you want is a list of your DTO Class.

For this you would have to have a DTO Class like this one:

public class TestRequest {
    private String name;
    private Integer count;
}

The result would be a list of your DTO Class like this:

        List<TestRequest> toReturn = new ArrayList<>();
        toReturn.add(TestRequest.builder()
                        .name("a")
                        .count(1)
                .build());
        toReturn.add(TestRequest.builder()
                        .name("b")
                        .count(2)
                .build());

The resulting request would be as follows:

[
    {
        "name": "a",
        "count": 1
    },
    {
        "name": "b",
        "count": 2
    }
]
  •  Tags:  
  • Related