JSONObject.toJSONString
在Java開發中,通常需要將一個實體對象轉換成Json字符串,使用FastJson來實現這種轉換十分方便,只要使用FastJson中JSONObject靜態類提供的toJSONString()靜態方法即可,但是如果不了解這個方法,很有可能就會使得轉換后的Json不合自己的要求。
使用JSONObject把實體對象轉換成Json字符串時,如果實體對象中有些屬性的值為null,則默認轉換后的Json字符串中是不包含這些值為null的屬性。
User user = new User(); user.setId(1L); user.setUsername("張三"); user.setPassword(""); user.setMobile(null); user.setCountry("中國"); user.setCity("武漢"); String jsonUser = null; /** * 指定排除屬性過濾器和包含屬性過濾器 * 指定排除屬性過濾器:轉換成JSON字符串時,排除哪些屬性 * 指定包含屬性過濾器:轉換成JSON字符串時,包含哪些屬性 */ String[] excludeProperties = {"country", "city"}; String[] includeProperties = {"id", "username", "mobile"}; PropertyPreFilters filters = new PropertyPreFilters(); PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); excludefilter.addExcludes(excludeProperties); PropertyPreFilters.MySimplePropertyPreFilter includefilter = filters.addFilter(); includefilter.addIncludes(includeProperties); /** * 情況一:默認忽略值為null的屬性 */ jsonUser = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat); System.out.println("情況一:\n" + jsonUser); /** * 情況二:包含值為null的屬性 */ jsonUser = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue); System.out.println("情況二:\n" + jsonUser); /** * 情況三:默認忽略值為null的屬性,但是排除country和city這兩個屬性 */ jsonUser = JSONObject.toJSONString(user, excludefilter, SerializerFeature.PrettyFormat); System.out.println("情況三:\n" + jsonUser); /** * 情況四:包含值為null的屬性,但是排除country和city這兩個屬性 */ jsonUser = JSONObject.toJSONString(user, excludefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue); System.out.println("情況四:\n" + jsonUser); /** * 情況五:默認忽略值為null的屬性,但是包含id、username和mobile這三個屬性 */ jsonUser = JSONObject.toJSONString(user, includefilter, SerializerFeature.PrettyFormat); System.out.println("情況五:\n" + jsonUser); /** * 情況六:包含值為null的屬性,但是包含id、username和mobile這三個屬性 */ jsonUser = JSONObject.toJSONString(user, includefilter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue); System.out.println("情況六:\n" + jsonUser); }
JSONObject.parseObject
result格式:
{
"success":"true",
"data":{
"shop_uid":"123"
}
JSONObject shop_user =JSON.parseObject(result);
JSON.parseObject(shop_user.getString("data")).getString("shop_uid")
