java tojson_使用java注解实现toJson方法

该代码示例展示了如何使用自定义注解`JsonFieldFormat`和`JsonClassFormat`来格式化Java对象并将其转换为JSON格式。`JsonFormater`类通过反射获取对象字段,并根据注解的类型和名称生成JSON字符串。示例中,`User`和`Person`类被转换,突出显示了注解在处理复杂数据类型如ArrayList时的作用。
摘要由CSDN通过智能技术生成

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;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.HashMap;

class JsonFormaterTest{

public static void main(String[] args){

ArrayList fruits = new ArrayList();

fruits.add("apple");

fruits.add("orange");

User user = new User("abc@163.com", "abc", fruits);

JsonFormater jf = new JsonFormater(user);

System.out.println(jf.toJson(1));

Person person = new Person("abc@163.com", "abc", fruits);

jf = new JsonFormater(person);

System.out.println(jf.toJson(2));

}

}

class JsonFormater{

private Object object;

public JsonFormater(Object obj){

this.object = obj;

}

public ArrayList> toJsonArr(){

Field[] fields = this.object.getClass().getDeclaredFields();

ArrayList> json = new ArrayList>();

for(Field field : fields){

if(field.isAnnotationPresent(JsonFieldFormat.class)){

JsonFieldFormat jff = (JsonFieldFormat) field.getAnnotation(JsonFieldFormat.class);

ArrayList aFieldArr = new ArrayList();

String fieldName;

if(jff.name().equals("")){

fieldName = field.getName();

}

else {

fieldName = jff.name();

}

aFieldArr.add(fieldName);

try {

if (jff.type().equals("String")) {

Field aField = this.object.getClass().getDeclaredField(field.getName());

aField.setAccessible(true);

String aFieldValue = (String) aField.get(this.object);

aFieldArr.add("\""+aFieldValue+"\"");

// Method aFieldMethod = this.object.getClass().getDeclaredMethod(fieldName, null);

// aFieldMethod.setAccessible(true);

// String aFieldValue = (String) aFieldMethod.invoke(this.object, null);

} else if (jff.type().equals("ArrayList")) {

Field aField = this.object.getClass().getDeclaredField(field.getName());

aField.setAccessible(true);

ArrayList aFieldValue = (ArrayList) aField.get(this.object);

String fieldValues = "[";

for (int i = 0; i < aFieldValue.size(); i++) {

String str = aFieldValue.get(i);

fieldValues = fieldValues + "\"" + str + "\"";

if(i!=aFieldValue.size()-1){

fieldValues = fieldValues + ",";

}

}

fieldValues = fieldValues + "]";

aFieldArr.add(fieldValues);

}

json.add(aFieldArr);

}

catch (Exception e){

//

}

}

else {

// System.out.println("unused field");

// System.out.println(field.getName());

}

}

return json;

}

public ArrayList> toJsonArr2(){

Field[] fields = this.object.getClass().getDeclaredFields();

ArrayList> json = new ArrayList>();

if(this.object.getClass().isAnnotationPresent(JsonClassFormat.class)){

JsonClassFormat jcf = (JsonClassFormat) this.object.getClass().getAnnotation(JsonClassFormat.class);

String[] nameTypes = jcf.nameTypes();

int len = nameTypes.length;

int fieldLen = len/3;

HashMap types = new HashMap();

HashMap aliasNames = new HashMap();

for(int i=0;i

types.put(nameTypes[i*3], nameTypes[i*3+1]);

aliasNames.put(nameTypes[i*3], nameTypes[i*3+2]);

}

for(Field field : fields){

if(types.get(field.getName()) != null){

ArrayList aFieldArr = new ArrayList();

String fieldName;

if(aliasNames.get(field.getName()).equals("")){

fieldName = field.getName();

}

else {

fieldName = aliasNames.get(field.getName());

}

aFieldArr.add(fieldName);

try{

Field aField = this.object.getClass().getDeclaredField(field.getName());

aField.setAccessible(true);

if(types.get(field.getName()).equals("String")){

String aFieldValue = (String) aField.get(this.object);

aFieldArr.add("\""+aFieldValue+"\"");

}

else if(types.get(field.getName()).equals("ArrayList")){

ArrayList aFieldValue = (ArrayList) aField.get(this.object);

String fieldValues = "[";

for(int i=0;i

String str = aFieldValue.get(i);

fieldValues = fieldValues + "\"" + str + "\"";

if(i!=aFieldValue.size()-1){

fieldValues = fieldValues + ",";

}

}

fieldValues = fieldValues + "]";

aFieldArr.add(fieldValues);

}

json.add(aFieldArr);

}

catch (Exception e){

//

}

}

else{

// System.out.println("unused field");

// System.out.println(field.getName());

}

}

}

return json;

}

public String toJson(int x){

ArrayList> json;

if(x==1){

json = toJsonArr();

}

else{

json = toJsonArr2();

}

ArrayList allFields = new ArrayList();

for(int i=0;i

ArrayList str = json.get(i);

allFields.add("\""+str.get(0)+"\":"+str.get(1)+"");

}

String jsonStr = "{";

for(int i=0;i

jsonStr = jsonStr + allFields.get(i);

if(i!=allFields.size()-1){

jsonStr = jsonStr + ",";

}

}

jsonStr = jsonStr + "}";

return jsonStr;

}

}

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@interface JsonFieldFormat {

String type() default "";

String name() default "";

}

class User{

@JsonFieldFormat(type="String")

private String email;

@JsonFieldFormat(type="String", name="alias")

private String name;

@JsonFieldFormat(type="ArrayList")

private ArrayList favFruits;

private String otherField;

public User(String email, String name, ArrayList favFruits){

this.email = email;

this.name = name;

this.favFruits = favFruits;

}

}

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@interface JsonClassFormat {

String[] nameTypes();

}

@JsonClassFormat(nameTypes={"email", "String", "", "name", "String", "alias", "favFruits", "ArrayList", ""})

class Person{

private String email;

private String name;

private ArrayList favFruits;

private String otherField;

public Person(String email, String name, ArrayList favFruits){

this.email = email;

this.name = name;

this.favFruits = favFruits;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值