前几天写了一个通用JSON生成器,但是用着用着觉得意犹未尽,不是特别顺手。原因有二:
- 上个方法要求filed的域就是json数据中的域名称,这样很受限,特别是在发送给前端、或者JNI时,可能C语言的风格是使用下划线,而不是驼峰法,比如userName是java风格,而user_name则C语言常常用,那么,如果要让我把filed名字都变成user_name这种形式,我会受不了的。
- 对于有些域而言,可能我并不想输出,比如我仅仅利用该域做运算,而不想发送给前端,那么前者就得要求重写一个类了。这样也很不友好。
因此,我利用注解的方法重写了上个类。1、创建Output注解;2、然后在输出类中添加Output注解;3、然后在注解中添加要返回的域的名字,对于不想输出的域,不添加注解即可。
Output.java[注解类]
package com.dacas.json.entity;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by dave on 2016/3/12.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Output {
public String value();//Output中使用value作为注解域,使用value可以作为“快捷方式”
}
GenerateJSON.java
package com.dacas.json.entity;
import org.json.JSONArray;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.util.List;
/**
* Created by dave on 2016/3/6.
*/
public class GenerateJSON {
public static <T> JSONObject getJSON(T t,Class<T> tClass) throws Exception{
Field[] fileds = tClass.getFields();
JSONObject jsonObject = new JSONObject();
for (Field field:fileds){
Output output = field.getAnnotation(Output.class);
if(output != null){
String name = output.value();
Object value = field.get(t);
jsonObject.put(name,value);
}
}
return jsonObject;
}
public static <T> JSONArray getJSON(List<T> tlist,Class<T> tClass) throws Exception{
JSONArray jsonArray = new JSONArray();
for(T tmpT:tlist){
jsonArray.put(getJSON(tmpT,tClass));
}
return jsonArray;
}
public static <T> String getJSONStr(T t,Class<T> tClass) throws Exception{
JSONObject object = getJSON(t,tClass);
return object.toString();
}
public static <T> String getJSONStr(List<T> tList,Class<T> tClass) throws Exception{
JSONArray array = getJSON(tList,tClass);
return array.toString();
}
}
Test.java[测试java实体类]
package com.dacas.json.entity;
/**
* Created by dave on 2016/3/6.
*/
public class Test {
@Output("_id")
public int id;
public String value;
public Test(int id,String value){
this.id = id;
this.value = value;
}
}
【main类】
import com.dacas.json.entity.GenerateJSON;
import com.dacas.json.entity.Test;
import java.util.LinkedList;
/**
* Created by dave on 2016/3/6.
*/
public class TestString {
public static void main(String[] args){
try {
LinkedList<Test> testList = new LinkedList<>();
for(int i = 0;i<10;i++){
Test test = new Test(i,i+"");
testList.add(test);
}
String result = GenerateJSON.getJSONStr(testList,Test.class);
System.out.println(result);
}catch (Exception ex){
ex.printStackTrace();
}
}
}