'How to convert a JSON request into a list of specific format n spring?
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.
Solution 1:[1]
Try using a zip on the value lists to create a list of tuples containing the nth element of each.
Solution 2:[2]
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;
}
An example of the original DTO class could be:
public class TestRequestDTO {
private Integer id;
private List<String> values;
}
The result would be a list of your DTO Class like this:
List<TestRequestDTO> dtoClassList = new ArrayList<>();
List<TestRequest> toReturn = new ArrayList<>();
for (int i = 0; i < dtoClassList.size(); i++) {
for (int j = 0; j < dtoClassList.get(i).getValues().size(); j++) {
if (i+1 != dtoClassList.size()) {
toReturn.add(TestRequest.builder()
.name(dtoClassList.get(i).getValues().get(j))
.count(dtoClassList.get(i + 1).getValues().get(j))
.build());
}
}
}
The resulting request would be as follows:
[
{
"name": "a",
"count": 1
},
{
"name": "b",
"count": 2
}
]
Solution 3:[3]
Your problem is to generate a set using members of two different sets in the original JSON file according to positions. The code will rather long if you try to do it in Java.
It is easy to accomplish this in SPL, the open-source Java package. Three lines of code are enough:
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as convert.splx and invoke it in Java as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call convert()");
st.execute();
…
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Matan Baruch |
Solution 2 | |
Solution 3 |