Issue
I have an object inside another object. When I ask key1
value in Servlet.java
with ObjectMapper I will get A(key1={key2=[1, 5, 7]})
, but I'd like to know how to separate key2
List value.
String input: {"key1":{"key2":[1,5,7]}}
Final result: 13
-> calculated from key2 array values (1 + 5 + 7)
Basically, I've already done everything, but getting values from key2 is still missing.
A.java
package servlet;
import lombok.Data;
@Data
public class A {
public Object key1;
}
B.java
package servlet;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class B{
List<Integer> key2 = new ArrayList<>();
}
Servlet.java
package servlet;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.stream.Collectors;
@WebServlet("/validate")
public class Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.getWriter().print("Hello!");
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String input = request.getReader().lines().collect(Collectors.joining("/n"));
A a = new ObjectMapper().readValue(input, new TypeReference<A>() {});
System.out.println(a); // A(key1={key2=[1, 5, 7]})
System.out.println(a.getKey1()); // {key2=[1, 5, 7]}
// Object in object ?
int sum = 0;
String output = new ObjectMapper().writeValueAsString(sum);
response.getWriter().write(output);
}
}
How am I able to separate key2
from it to calculate the sum of key2 array values?
Another restriction is that I cannot use split, replace, match etc.
Solution
So basically, I only needed to do was just use B class instead of Object
package servlet;
import lombok.Data;
@Data
public class A {
public B key1;
}
and in servlet ask from A class both key1, key2 and loop them
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String input = request.getReader().lines().collect(Collectors.joining("/n"));
A a = new ObjectMapper().readValue(input, new TypeReference<A>() {});
int sum = 0;
for (Integer b: a.getKey1().getKey2()) {
sum += b;
}
String output = new ObjectMapper().writeValueAsString(sum);
response.getWriter().write(output);
}
Answered By - AvocadoGirl
Answer Checked By - Marie Seifert (JavaFixing Admin)