我有一个模型类...
public class Incident implements Serializable {
private Long id;
private Integer refNo;
private String type;
private Double lossAmt;
private Date incidentDate;
private Date incidentTime;
private Date reportingDate;
}
FTL 就像...
<form action="saveIncident.do" method="POST" >
<input type="text" name="type" value="A">
<input type="text" name="refNo" value="546">
<input type="text" name="lossAmt" value="45000">
<input type="text" name="incidentDate" value="10/05/2017">
<input type="text" name="reportingDate" value="18/05/2017">
<input type="submit" value="Save">
</form>
我正在尝试从 HttpServletRequest 请求获取对象
Map<String, String[]> map = request.getParameterMap();
String formData = new Gson().toJson(map);
以上代码返回 formData
值 {"type":["A"],"lossAmt":["45000"],"incidentDate":["10/05/2017"],"reportingDate":["18/05/2017"],"refNo":[""]}
.然后我打电话..
Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
Incident incident = gson.fromJson(formData, Incident.class);
此抛出com.google.gson.JsonSyntaxException
但是,当我使用 .. 替换所有数组符号 [ & ]
时
formData = formData.replaceAll("[\\[ \\]]", ""); // {"type":"A","lossAmt":"45000" ....
然后就可以正常工作了。因此,如何在不替换数组符号的情况下转换为事件对象?
最佳答案
恕我直言,问题已经出现在您解析参数的地方,
Map<String, String[]> map = request.getParameterMap();
String formData = new Gson().toJson(map);
如您所见,您的参数是数组。
{"type":["A"], ... }
请注意,Gson 不会将数组转换为标量(简单变量)本身。
我会尝试:
Map<String, String> params = new HashMap<>();
Map<String, String[]> parameterMap = request.getParameterMap();
parameterMap.forEach((key,value) -> { params.put(key, value[0]); });
为了简化起见,这里我们假设非空值并忽略其他(多个)值(如果存在)。你应该处理它
关于java - 将 Http Servlet 请求转换为 json 到我定义的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44068216/