1.map转json
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "a");
map.put("b", "123");
JSONObject json = new JSONObject(map);
2.map转string
Map<String, Object> map = new HashMap<>();
map.put("a", "b");
String s = JSONObject.toJSONString(map);
3.json转string
JSONObject json = new JSONObject();
json.put("c", "v");
json.put("z", "123n);
json.toJSONString();
4.json转map
JSONObject json = new JSONObject();
json.put("ccc", "321");
json.put("bbb", "123");
Map<String, Object> map = (Map<String, Object>)json;
5.string转json
String str = "{\"username\":\"dsad\",\"qwewqe\":\"123\"}";
JSONObject json = JSONObject.parseObject(str);
6.json转map
private static Object json_to_map(String json)
{
Object array = JSONObject.parse(json);
if(array instanceof JSONArray){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for (int i= 0;i<((JSONArray) array).size();i++)
{
JSONObject myjObject = ((JSONArray)array).getJSONObject(i);
Map<String,Object> ret1 = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : myjObject.entrySet()) {
if(isJson(entry.getValue().toString()))
{
ret1.put(entry.getKey(), json_to_map(entry.getValue().toString()));
}else{
log.info("JSONObject=> key:" + entry.getKey().toString()+" value:"+entry.getValue());
ret1.put(entry.getKey(), entry.getValue());
}
}
list.add(ret1);
}
return list;
}
else if(array instanceof JSONObject){
Map<String,Object> ret = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : ((JSONObject)array).entrySet()) {
if(isJson(entry.getValue().toString()))
{
ret.put(entry.getKey(), json_to_map(entry.getValue().toString()));
}else{
log.info("JSONObject=> key:" + entry.getKey().toString()+" value:"+entry.getValue());
ret.put(entry.getKey(), entry.getValue());
}
}
return ret;
}
return null;
}
判断是否为json串
/*
*字符串{},[]都是正确的json串
*/
public static boolean isJson(String str){
if (StringUtils.isBlank(str)){
return false;
}
try{
Object parse = JSON.parse(str);
if (parse instanceof JSONObject || parse instanceof JSONArray){
return true;
}
}catch (Exception e){
return false;
}
return false;
}
判断Object类型
Object ret = json_to_map(jsonmap);
log.info(ret == null ? "null" : ret instanceof HashMap ? "HashMap" : ret instanceof ArrayList ? "ArrayList" : ret.getClass().getTypeName());
Java 使用falstjson包 技巧