Conversion between json and objects - mainly date format issues

1. Summary
1. The date format cannot be arbitrary, it must be fixed before it can be automatically converted, whether using FastJson or JSONUtils
2. Exception handling for unavoidable json passed parameter type or format errors, optimistic thinking

2. Code
1, FastJson:
com.alibaba.fastjson.JSON.parseObject(menuObjectData,Menu.class);


2 、 JSONUtils :
/**
	 * Description: Convert json string to object   
	 * @param jsonStr
	 * @param beanClass
	 * @return
	 */
	public static Object jsonStrToObject(String jsonStr, Class beanClass){
		if(null == jsonStr || "".equals(jsonStr.trim())) {
			return null;
		}
		
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		jsonConfig.setRootClass(beanClass);	 
		String[] dateFamates = new String[] {"yyyy-MM-dd HH:mm:ss", //You can add any date format to match the json string
				"yyyy_MM_dd",
				"HH_mm_ss",
				"yyyyMMdd",
				"yyyyMMddHHmmss",
				"Yyyy year MM month dd day HH hour mm minute ss second",
				"yyyy-MM-dd HH:mm:ss:SSSSSS"};
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFamates));
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFamates));
        Object obj=JSONObject.toBean(jsonObject, jsonConfig);
		return obj;
	}

3, json string type verification
/***
     *
     * Get JSON type
     * Judgment rules
     * Determine if the first letter is { or [ If it is not, it is not a JSON formatted text
     * @param str
     * @return
     */  
    public static JsonType getJSONType(String jsonStr){  
    	//Check if the string is empty
    	//TextUtils.isEmpty(CharSequence str), when the parameter in parentheses is (null) or (""), return true.
        if(PubUtils.isSEmptyOrNull(jsonStr)){  
            return JsonType.JSON_TYPE_EMPTY;  
        }  
  
        final char[] strChar = jsonStr.substring(0, 1).toCharArray();  
        final char firstChar = strChar[0];  
  
        if(firstChar == '{'){  
            return JsonType.JSON_TYPE_OBJECT; //Object type
        }else if(firstChar == '['){   
            return JsonType.JSON_TYPE_ARRAY; //Array type  
        }else{  
            return JsonType.JSON_TYPE_ERROR; //The parameter is not a json string
        }  
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326256808&siteId=291194637