实体与JSON的相互转换(简单类型)

这篇博客介绍了如何在Java中使用注解进行JSON与实体对象之间的相互转换,包括利用工具类进行转换的方法。
摘要由CSDN通过智能技术生成

json的注解

  

package com.leqienglish.annotation;

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

@Target(ElementType.FIELD) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
public @interface JSON {
	/**
	 * json 的key值
	 * @return
	 */
	String name();
}

实体与JSON的相互转换工具类

package com.leqienglish.annotation.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.activation.FileDataSource;

import org.json.JSONException;
import org.json.JSONObject;

import com.leqienglish.annotation.JSON;
/**
 * json与实体间的相互转换 
 * 不支持嵌套json 与嵌套实体
 * 被转换的实体必须有set,get方法
 * @author guona
 *
 */
public class EntityAndJSON {
	/**
	 * 将实体转换为json字符串
	 * 
	 * @param t
	 * @return
	 * @throws Exception
	 */
	public static <T> String toJSON(T t) throws Exception {
		JSONObject jsonObject = new JSONObject();
		Field[] fieldArr = t.getClass().getDeclaredFields();
		for (Field field : fieldArr) {
			JSON json = field.getAnnotation(JSON.class);
			if (json != null) {
				Object value = getValue(t, field);
				jsonObject.put(json.name(), value);
			}
			System.err.println(field.getName());

		}
		return jsonObject.toString();
	}

	/**
	 * 将JSON转换为Object
	 * 
	 * @param jsonObject
	 * @param clazT
	 * @return
	 * @throws Exception
	 */
	public static <T> T json2Object(String jsonSt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值