@JSONField的一些使用基础

@JSONField介绍

fastjson是阿里巴巴出品的快速解析json的一个工具,

 @JSONField就是里面为数不多的注解之一.也是最为重要的注解.它的内容如下:

/*
 * Copyright 1999-2017 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.fastjson.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @author wenshao[szujobs@hotmail.com]
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
public @interface JSONField {
    /**
     * config encode/decode ordinal
     * @since 1.1.42
     * @return
     */
    int ordinal() default 0;

    String name() default "";

    String format() default "";

    boolean serialize() default true;

    boolean deserialize() default true;

    SerializerFeature[] serialzeFeatures() default {};

    Feature[] parseFeatures() default {};
    
    String label() default "";
    
    /**
     * @since 1.2.12
     */
    boolean jsonDirect() default false;
    
    /**
     * Serializer class to use for serializing associated value.
     * 
     * @since 1.2.16
     */
    Class<?> serializeUsing() default Void.class;
    
    /**
     * Deserializer class to use for deserializing associated value. 
     * 
     * @since 1.2.16 
     */
    Class<?> deserializeUsing() default Void.class;

    /**
     * @since 1.2.21
     * @return the alternative names of the field when it is deserialized
     */
    String[] alternateNames() default {};

    /**
     * @since 1.2.31
     */
    boolean unwrapped() default false;
}

其中里面最常用的属性是:name,format,serialize,deserialize,serializeUsing,deserializeUsing

fastjson编程式如何使用以及痛点

一般最常见的是这两个方法:

JSON.toJSONString(object):序列化对象,生产字符串
JSON.parse(text):反序列化对象,字符串转json

对于一般的没有什么变更的操作来说,这两个其实够用了.

但有时候情况会有些特殊,比如说:某个字段我想转成json时换个键名.或者我忽略某个字段等特殊操作,如果用编程式开发的话实在是有些烦闷的.比较坑爹.用注解的方式就很不错.

 

采用注解:

一个简单的demo如下:

public class JSonTest {

	private String id ="111";
	
	private String name ="tom ";

        private Date date = new Date();

    ...getter/setter
}
	
	
	
public static void main(String[] args) {
		System.out.println(JSON.toJSONString(new JSonTest()));
}

 

如果此时我想将这个类转成json,但要像"userid:111,name:tom"注意是userid,而不是id,那么这样既可.

    @JSONField(name="userid")
	private String id ="111";
	
	private String name ="tom ";

打印结果:{"date":1561545203036,"name":"tom ","userid":"111"}

加上这个注解使用name属性不止可以由类转成json,还可以解决由于json转成类时字段不一致的问题

如果我还想将userid放到前面形成{,"userid":"111","name":"tom "}这样呢?如下即可,ordinal是用来排序的.

@JSONField(name="userid",ordinal=0)
	private String id ="111";
	@JSONField(ordinal=1)
	private String name ="tom ";

如果我在序列化的时候想过滤掉name这个字段怎么做呢?如下:

@JSONField(serialize = false)
	private String name ="tom ";

如果我在反序列化的时候想过滤掉呢?如下:

@JSONField(deserialize = false)

如果我想让我的date时间变成特殊格式呢?

@JSONField(format = "yyyy-MM-dd")
	private Date date = new Date();

如果我想在生成json或者解析json时获得的对象名字前面都加上"aaa"呢?这就需要具体的定制了.下面是解析和生成结合到了一起

@JSONField(deserializeUsing = NameDeserializer.class,serializeUsing=NameDeserializer.class)
	private String name ="tom ";
class NameDeserializer implements ObjectDeserializer,ObjectSerializer{

		@Override
		public <T> T deserialze(DefaultJSONParser parser, Type type,
				Object fieldName) {
			String val = (String) parser.parse();
			return (T) ("aaa " + val);
		}

		@Override
		public int getFastMatchToken() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public void write(JSONSerializer serializer, Object object,
				Object fieldName, Type fieldType, int features)
				throws IOException {
			
			serializer.write("aaa " + object);
		}
		
	}

 

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值