我有一个模特班......
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 request
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" ....
然后工作正常。因此,如何在不替换数组符号的情况下转换为Incident
对象?
答案 0 :(得分:2)
恕我直言,这个问题已经到了解析参数的地步,
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]); });
为简化起见,这里我们假设非空值并忽略其他(多个)值(如果存在)。你应该处理它