我在另一个对象中有一个对象。当我用ObjectMapper询问Servlet.java
中的key1
值时,我会得到A(key1={key2=[1, 5, 7]})
,但我想知道如何分离key2
-List值。
字符串输入:{"key1":{"key2":[1,5,7]}}
最终结果:13
->calculated from key2 array values (1 + 5 + 7)
基本上,我已经完成了所有操作,但仍然缺少从key2获取值的功能。
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);
}
}
如何将key2
从中分离出来以计算key2数组值的总和?
另一个限制是我不能使用拆分、替换、匹配等
所以基本上,我只需要使用B类而不是Object
package servlet;
import lombok.Data;
@Data
public class A {
public B key1;
}
在servlet中,从A类询问key1和key2,并循环它们
@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);
}