项目中使用Ribbon传递form表单数据遇到一个数据转换问题:
使用fastJson转换LinkedMultiValueMap时报错
String jsonString = "{\"ownerId\":\"186\",\"ownerRole\":\"AGENT\",\"settleCardId\":null,\"group\":\"PAY\"," +
"\"organization\":null}";
LinkedMultiValueMap params = JSON.parseObject(jsonString, LinkedMultiValueMap.class);
System.out.println(params);
错误信息:
Exception in thread "main" com.alibaba.fastjson.JSONException: java.lang.String cannot be cast to java.util.List
at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:630)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:348)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:252)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:471)
at com.yp.ribbonconsume.TestMain.main(TestMain.java:47)
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List
at org.springframework.util.LinkedMultiValueMap.put(LinkedMultiValueMap.java:38)
at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:447)
at com.alibaba.fastjson.parser.deserializer.MapDeserializer.deserialze(MapDeserializer.java:64)
at com.alibaba.fastjson.parser.deserializer.MapDeserializer.deserialze(MapDeserializer.java:41)
at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:626)
... 4 more
原因是因为LinkedMultiValueMap的value是List<V>类型,赶时间写了一个比较笨的方法
String jsonString = "{\"ownerId\":\"186\",\"ownerRole\":\"AGENT\",\"settleCardId\":null,\"group\":\"PAY\"," +
"\"organization\":null}";
JSONObject object = JSONObject.parseObject(jsonString);
Iterator it = object.keySet().iterator();
StringBuilder sb = new StringBuilder("{");
while (it.hasNext()) {
String key = (String) it.next();
Object value = object.getString(key);
if (value == null) {
sb.append(JSON.toJSONString(key)).append(":").append(value).append(",");
} else {
List<String> list = Collections.singletonList(value.toString());
sb.append(JSON.toJSONString(key)).append(":").append(JSON.toJSONString(list)).append(",");
}
}
sb.append("}");
sb.deleteCharAt(sb.length()-2);
System.out.println(sb.toString());
LinkedMultiValueMap params = JSON.parseObject(sb.toString(), LinkedMultiValueMap.class);
System.out.println(params);
如果各位有好的方法,烦请告之,不慎感激!!!