下面列出了怎么用com.alibaba.fastjson.annotation.JSONField的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* <p class="detail">
* 功能:判断字段类型是否为时间类型,若字段写了多个注解则优先级为DateTimeFormat(spring)>JSONField(fastjson)>JsonFormat(jackson),异常就返回""
* </p>
*
* @param className :类名
* @param fieldName :字段名
* @return boolean
* @author Kings
* @date 2019.11.02
*/
private String getDayPattern(String className, String fieldName) {
try {
Class<?> parseClass = Class.forName(className);
DateTimeFormat dateTimeFormat = parseClass.getDeclaredField(fieldName).getAnnotation(DateTimeFormat.class);
if (dateTimeFormat != null) {
return dateTimeFormat.pattern();
}
JSONField jsonField = parseClass.getDeclaredField(fieldName).getAnnotation(JSONField.class);
if (jsonField != null) {
return jsonField.format();
}
JsonFormat jsonFormat = parseClass.getDeclaredField(fieldName).getAnnotation(JsonFormat.class);
if (jsonFormat != null) {
return jsonFormat.pattern();
}
return "";
} catch (Exception e) {
return "";
}
}
/**
* <p class="detail">
* 功能:判断字段类型是否为时间类型,若字段写了多个注解则优先级为DateTimeFormat(spring)>JSONField(fastjson)>JsonFormat(jackson),异常就返回""
* </p>
*
* @param className :类名
* @param fieldName :字段名
* @return boolean
* @author Kings
* @date 2019.11.02
*/
private String getDayPattern(String javaDirPath,String className, String fieldName) {
try {
Class<?> parseClass = getCompileClass(javaDirPath,className);
DateTimeFormat dateTimeFormat = parseClass.getDeclaredField(fieldName).getAnnotation(DateTimeFormat.class);
if (dateTimeFormat != null) {
return dateTimeFormat.pattern();
}
JSONField jsonField = parseClass.getDeclaredField(fieldName).getAnnotation(JSONField.class);
if (jsonField != null) {
return jsonField.format();
}
JsonFormat jsonFormat = parseClass.getDeclaredField(fieldName).getAnnotation(JsonFormat.class);
if (jsonFormat != null) {
return jsonFormat.pattern();
}
return "";
} catch (Exception e) {
return "";
}
}
@JSONField(serialize = false)
public Map<String, String> getRmqProperties() {
HashMap<String, String> propertyMap = new HashMap<>();
if (StringUtils.isNotBlank(getKey()))
propertyMap.put(MessageConst.PROPERTY_KEYS, getKey());
if (StringUtils.isNotBlank(getTags()))
propertyMap.put(MessageConst.PROPERTY_TAGS, getTags());
propertyMap.put(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, createUniqID());
Map<String, String> msgProperties = this.getMsgProperties();
if (msgProperties != null) {
propertyMap.putAll(msgProperties);
}
// PROPERTY_WAIT_STORE_MSG_OK 这个属性没用。
//propertyMap.put(MessageConst.PROPERTY_WAIT_STORE_MSG_OK, Boolean.toString(true));
return propertyMap;
}
public MyFieldSerializer(FieldInfo fieldInfo){
this.fieldInfo = fieldInfo;
fieldInfo.setAccessible(true);
this.double_quoted_fieldPrefix = '"' + fieldInfo.getName() + "\":";
this.single_quoted_fieldPrefix = '\'' + fieldInfo.getName() + "\':";
this.un_quoted_fieldPrefix = fieldInfo.getName() + ":";
JSONField annotation = fieldInfo.getAnnotation(JSONField.class);
if (annotation != null) {
for (SerializerFeature feature : annotation.serialzeFeatures()) {
if (feature == SerializerFeature.WriteMapNullValue) {
writeNull = true;
}
}
}
}
/**
* Gets a query that can be used to query the subclass objects in this relation.
*
* @param clazz The AVObject subclass.
* @return A AVQuery that restricts the results to objects in this relations.
*/
@JSONField(serialize=false)
public AVQuery<T> getQuery(Class<T> clazz) {
if (getParent() == null || StringUtil.isEmpty(getParent().getObjectId())) {
throw new IllegalStateException("unable to encode an association with an unsaved AVObject");
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("object", Utils.mapFromPointerObject(AVRelation.this.getParent()));
map.put("key", AVRelation.this.getKey());
String targetClassName = getTargetClass();
if (StringUtil.isEmpty(targetClassName)) {
targetClassName = getParent().getClassName();
}
AVQuery<T> query = new AVQuery<T>(targetClassName, clazz);
query.addWhereItem("$relatedTo", null, map);
if (StringUtil.isEmpty(getTargetClass())) {
query.getParameters().put("redirectClassNameForKey", this.getKey());
}
return query;
}
/**
* Get data stream in blocking mode.
* @return data stream.
* @throws Exception for file not found or io problem.
*/
@JSONField(serialize = false)
public InputStream getDataStream() throws Exception {
String filePath = "";
if(!StringUtil.isEmpty(localPath)) {
filePath = localPath;
} else if (!StringUtil.isEmpty(cachePath)) {
filePath = cachePath;
} else if (!StringUtil.isEmpty(getUrl())) {
File cacheFile = FileCache.getIntance().getCacheFile(getUrl());
if (null == cacheFile || !cacheFile.exists()) {
FileDownloader downloader = new FileDownloader();
downloader.execute(getUrl(), cacheFile);
}
if (null != cacheFile) {
filePath = cacheFile.getAbsolutePath();
}
}
if(!StringUtil.isEmpty(filePath)) {
logger.d("dest file path=" + filePath);
return FileCache.getIntance().getInputStreamFromFile(new File(filePath));
}
logger.w("failed to get dataStream.");
return null;
}
/**
* 获取参数Key Set
* @return
*/
@JSONField(serialize=false)
public Set<String> getParamKeys() {
if (operationParam == null) {
return new HashSet<>(0);
}
return operationParam.keySet();
}
private static String getJSONFieldName(Field field) {
JSONField annotation = field.getAnnotation(JSONField.class);
if(annotation!=null){
return annotation.name();
}
return UNKNOWN;
}
@JSONField(serialize = false)
public Map<Long, List<Long>> getConsumeModeLongMapper() {
if (MapUtils.isEmpty(consumeModeMapper)) {
return null;
}
Map<Long, List<Long>> mapper = Maps.newHashMap();
for (Map.Entry<String, List<Long>> entry : consumeModeMapper.entrySet()) {
mapper.put(Long.parseLong(entry.getKey()), Lists.newArrayList(entry.getValue()));
}
return mapper;
}
public DefaultFieldDeserializer(ParserConfig config, Class<?> clazz, FieldInfo fieldInfo){
super(clazz, fieldInfo);
JSONField annotation = fieldInfo.getAnnotation();
if (annotation != null) {
Class<?> deserializeUsing = annotation.deserializeUsing();
customDeserilizer = deserializeUsing != null && deserializeUsing != Void.class;
}
}
@JSONField(serialize = false)
public Endpoint getEndpoint() {
Endpoint endpoint = new Endpoint();
endpoint.setIp(ip);
endpoint.setPort(port);
return endpoint;
}
/**
* Get request endpoint.
* @return endpoint.
*/
@JSONField(serialize = false)
public String getRequestRawEndpoint() {
if (StringUtil.isEmpty(getObjectId())) {
return "/1.1/classes/" + this.getClassName();
} else {
return "/1.1/classes/" + this.getClassName() + "/" + getObjectId();
}
}
@JSONField(serialize = false)
public Map<Long, List<Long>> getConsumeModeLongMapper() {
if (MapUtils.isEmpty(consumeModeMapper)) {
return null;
}
Map<Long, List<Long>> mapper = Maps.newHashMap();
for (Map.Entry<String, List<Long>> entry : consumeModeMapper.entrySet()) {
mapper.put(Long.parseLong(entry.getKey()), Lists.newArrayList(entry.getValue()));
}
return mapper;
}
@JSONField(serialize = false)
public RemotingCommandType getType() {
if (this.isResponseType()) {
return RemotingCommandType.RESPONSE_COMMAND;
}
return RemotingCommandType.REQUEST_COMMAND;
}
/**
* 读取get set方法
*
* @param cls
* @param methods
* @param fmmap
* @param haveJSONField
*/
private static void register(Class<?> cls, Method[] methods, Map<String, FieldMethod> fmmap,
boolean haveJSONField) {
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
try {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
JSONField fieldAnnotation = field.getAnnotation(JSONField.class);
if (haveJSONField && fieldAnnotation == null) {
continue;
}
String fieldGetName = parGetName(field);
String fieldSetName = ReflectUtil.parSetName(field);
Method fieldGetMet = getGetMet(methods, fieldGetName);
Method fieldSetMet = ReflectUtil.getSetMet(methods, fieldSetName);
if (fieldGetMet != null && fieldSetMet != null) {
FieldMethod fgm = new FieldMethod(fieldGetMet, fieldSetMet, field);
fmmap.put(fgm.getName(), fgm);
} else {
System.out.println("找不到set或get方法 " + cls.getName() + " field:" + field.getName());
}
} catch (Exception e) {
System.out.println("register field:" + cls.getName() + ":" + field.getName() + " " + e);
continue;
}
}
Class<?> scls = cls.getSuperclass();
if (scls != null) {
register(scls, scls.getDeclaredMethods(), fmmap, haveJSONField);
}
}
@JSONField(serialize = false)
public void setEncryptPassword(String password) {
if(StringUtils.isNotBlank(password)){
this.password = DbConfigEncryption.encrypt(password);
}else{
this.password = "";
}
}
@JsonIgnore
@JSONField(serialize = false, deserialize = false)
public void serializeFields() {
this.skillStr = JSONObject.toJSONString(skillList);
}
/** 共用变量 get set **/
@JSONField(name = Users.AGE)
public int getAge() {
return this.mAge;
}
@JSONField(serialize = false)
public void check() throws Exception {
if (StringUtils.isBlank(esTemplate) ||
StringUtils.isBlank(hiveDB) ||
StringUtils.isBlank(hiveTable) ||
StringUtils.isBlank(key) ||
StringUtils.isBlank(mrqueue) ||
StringUtils.isBlank(hdfsOutputPath) ||
StringUtils.isBlank(user) ||
StringUtils.isBlank(passwd) ||
StringUtils.isBlank(esWorkDir) ||
StringUtils.isBlank(server) ||
time <= 0) {
throw new Exception("param is wrong");
}
if (!StringUtils.isBlank(key)) {
List<String> keyList = getKeyList();
if (keyList == null || keyList.size() == 0) {
throw new Exception("key is blank, key:" + key);
}
for (String k : keyList) {
if (StringUtils.isBlank(k)) {
throw new Exception("key is blank, key:" + key);
}
}
}
if (hdfsOutputPath.endsWith("/")) {
hdfsOutputPath = hdfsOutputPath.substring(0, hdfsOutputPath.length() - 1);
}
// 拼接实际使用的路径
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String pathtag = esTemplate.trim() + "_" + dateFormat.format(time);
if (pathtag.length() > 100) {
pathtag = pathtag.substring(0, 100);
}
hdfsOutputPath = hdfsOutputPath + "/" + pathtag;
}
@JSONField(name = "server_version_string")
public String getServerVersionString() {
return serverVersionString;
}
@JSONField(name="headimgurl")
public void setHeadimgUrl(String headimgUrl) {
this.headimgUrl = headimgUrl;
}
@JsonIgnore
@JSONField(serialize = false)
public ParamFlowClusterConfig getClusterConfig() {
return rule.getClusterConfig();
}
@JsonIgnore
@JSONField(serialize = false)
public int getBurstCount() {
return rule.getBurstCount();
}
@JSONField(serialize = false)
public abstract Byte getCommand();
@JSONField(name="all-exceptions")
public List<FlinkJobExceptionDetailDTO> getAllExceptions() {
return allExceptions;
}
public static String[] lookupParameterNames(AccessibleObject methodOrCtor) {
if (IS_ANDROID) {
return new String[0];
}
final Class<?>[] types;
final Class<?> declaringClass;
final String name;
Annotation[][] parameterAnnotations;
if (methodOrCtor instanceof Method) {
Method method = (Method) methodOrCtor;
types = method.getParameterTypes();
name = method.getName();
declaringClass = method.getDeclaringClass();
parameterAnnotations = method.getParameterAnnotations();
} else {
Constructor<?> constructor = (Constructor<?>) methodOrCtor;
types = constructor.getParameterTypes();
declaringClass = constructor.getDeclaringClass();
name = "<init>";
parameterAnnotations = constructor.getParameterAnnotations();
}
if (types.length == 0) {
return new String[0];
}
ClassLoader classLoader = declaringClass.getClassLoader();
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
String className = declaringClass.getName();
String resourceName = className.replace('.', '/') + ".class";
InputStream is = classLoader.getResourceAsStream(resourceName);
if (is == null) {
return new String[0];
}
try {
ClassReader reader = new ClassReader(is, false);
TypeCollector visitor = new TypeCollector(name, types);
reader.accept(visitor);
String[] parameterNames = visitor.getParameterNamesForMethod();
for (int i = 0; i < parameterNames.length; i++) {
Annotation[] annotations = parameterAnnotations[i];
if (annotations != null) {
for (int j = 0; j < annotations.length; j++) {
if (annotations[j] instanceof JSONField) {
JSONField jsonField = (JSONField) annotations[j];
String fieldName = jsonField.name();
if (fieldName != null && fieldName.length() > 0) {
parameterNames[i] = fieldName;
}
}
}
}
}
return parameterNames;
} catch (IOException e) {
return new String[0];
} finally {
IOUtils.close(is);
}
}
@JSONField(name = "Timeout")
public Integer getTimeout() {
return Timeout;
}
@JSONField(name="sub_button")
public void setSubButton(List<MenuButton> subButton) {
this.subButton = subButton;
}
/**
* 客服头像url
* @return
*/
@JSONField(name="kf_headimgurl")
public String getKfHeadimgurl() {
return kfHeadimgurl;
}
@JSONField(name = "packed_trx")
public String getPackedTrx() {
return packedTrx;
}