json字符串相关转换方法

/** json转换为Map
* @param jsonStr json
* @return map集合
*/
public static HashMap<String, String> json2HashMap(String jsonStr) 
{ 
HashMap<String, String> data = new HashMap<String, String>(); 
// 将json字符串转换成jsonObject 
JSONObject jsonObject = JSONObject.fromObject(jsonStr); 
Iterator<Object> it = jsonObject.keys(); 
// 遍历jsonObject数据,添加到Map对象 
while (it.hasNext()) 
{ 
String key = String.valueOf(it.next()); 
Object value = jsonObject.get(key); 
data.put(key, value.toString()); 
} 
return data; 
}

 

public static String toJson (Object object, DateFormat dateFormat) throws IOException {
ObjectMapper mapper = JacksonMapper.getInstance();
// 解决hibernate延迟加载
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
if (dateFormat != null) {
mapper.setDateFormat(dateFormat);
} else {
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
}
String json = getJsonStr(mapper, object);
return json;
}

  

原文地址:https://www.cnblogs.com/yangsy0915/p/4911925.html