使用Spring集成和我有一个JSON字符串(见下文)和下面的代码:
public SomethingBean convert(Message<?> inMessage) {...}
JSON字符串
{
"addressIdentification": {
"identifierType": "nemtom",
"addressIdentifier": "eztse"
},
"postcode": "BH1EH",
"country": "5"
}
我想用下面的方法签名:
public SomethingBean convert(Message<Map<String, ?>> inMessage) {...}
是否有可能将JSON字符串自动地图转换?
谢谢,V.
只需使用Spring集成开箱组件:
<json-to-object-trnsfrormer type="java.util.Map"/>
之前你SomethingBean
调用。
使用任何JSON解析库如GSON或杰克逊并将其转换成Java对象。
GSON:
String jsonString = "{\"addressIdentification\":{\"identifierType\":\"nemtom\",\"addressIdentifier\":\"eztse\"},\"postcode\":\"BH1EH\",\"country\":\"5\"}";
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(jsonString, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
for(Map.Entry<String, Object> entry:data.entrySet()){
System.out.println(entry.getKey()+":"+entry.getValue());
}
杰克逊:
String jsonString = "{\"addressIdentification\":{\"identifierType\":\"nemtom\",\"addressIdentifier\":\"eztse\"},\"postcode\":\"BH1EH\",\"country\":\"5\"}";
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println(jsonObject);
JSONObject addressIdentification = jsonObject.getJSONObject("addressIdentification");
System.out.println("identifierType:" + addressIdentification.get("identifierType"));
System.out.println("addressIdentifier:" + addressIdentification.get("addressIdentifier"));
System.out.println("postcode:" + jsonObject.get("postcode"));
System.out.println("country:"+jsonObject.get("country"));
输出:
identifierType:nemtom
addressIdentifier:eztse
postcode:BH1EH
country:5
阅读更多...