使用的jar包
json-lib-2.2.2-jdk15.jar
ezmorph-1.0.4.jar
commons-lang-2.1.jar
commons-logging-1.2.jar
commons-collections-3.2.2.jar
commons-beanutils-1.9.3.jar
代码如下:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class testJsonToMap {
public static Map<String, String> getMapFromJson(String jsonString) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Map<String, String> map = new HashMap<String, String>();
for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
String key = (String) iter.next();
String value=jsonObject.getString(key);
if(org.apache.commons.lang.StringUtils.isNotBlank(value)&&!"null".equalsIgnoreCase(value))
{
map.put(key, jsonObject.getString(key));
}
}
return map;
}
public static JSONObject mapToJson(Map<String, String> map) throws Exception {
//JSONArray array_test = new JSONArray();
//array_test.add(map);
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject;
}
public static void main(String[] args) throws Exception {
String jsonString = "{\"data\":\"test\",\"result\":\"200\",\"codeUrl\":\"url\",\"imageValue\":\"html\"}";
Map<String, String> map = new HashMap<String, String>();
//JSON转Map
map = getMapFromJson(jsonString);
System.out.print(map.get("data")+",");
System.out.print(map.get("result")+",");
System.out.print(map.get("codeUrl")+",");
System.out.println(map.get("imageValue"));
map.remove("imageValue");
//Map转JSON
JSONObject jsonObject = mapToJson(map);
System.out.println(jsonObject.toString());
}
}
(模拟效果,就不做trycatch异常处理了.....直接抛)
输出结果:
test,200,url,html
{"result":"200","codeUrl":"url","data":"test"}