JsonObject(gson)转bean

gson自带的转bean有格式要求,使用很不方便。浅浅的自己写了个支持复杂的类对象和List的方法
分享一下

package com.unary.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.una.comlog.Logger;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dontmind
 * @date 2023/9/25 16:05
 */
public class Json2BeanUtil {
    private static Logger logger = Logger.getLogger(Json2BeanUtil.class.getName());

    /**
     * 读gson任务参数
     * */
    public ProcessParam getParam(String path){
        ProcessParam processParam=new ProcessParam();
        String paramStr = processFileUtil.readFile(path);
        JsonObject jsonObject =new Gson().fromJson(paramStr, JsonObject.class);
        if (Json2BeanUtil.json2Bean(processParam,jsonObject)){
            return processParam;
        }else {
            return null;
        }
    }

    /**
     * 复杂gson转bean
     * */
    public static <T> boolean json2Bean(T bean, JsonObject jsonObject){
        try {
            Field[] fields = bean.getClass().getDeclaredFields();
            for (Field field : fields) {
                logger.info("param name:"+field.getName()+",type:"+field.getGenericType().toString());
                if (field.getGenericType().toString().equals("int")) {
                    JsonElement jsonElement=jsonObject.get(field.getName());
                    if (jsonElement!=null){
                        field.set(bean,jsonElement.getAsInt());
                    }
                } else if (field.getGenericType().toString().equals("long")) {
                    JsonElement jsonElement=jsonObject.get(field.getName());
                    if (jsonElement!=null){
                        field.set(bean,jsonElement.getAsLong());
                    }
                } else if (field.getGenericType().toString().equals("boolean")) {
                    JsonElement jsonElement=jsonObject.get(field.getName());
                    if (jsonElement!=null){
                        field.set(bean,jsonElement.getAsBoolean());
                    }
                }else if (field.getGenericType().toString().equals("class java.lang.String")||
                        field.getGenericType().toString().equals("java.lang.String")) {
                    JsonElement jsonElement=jsonObject.get(field.getName());
                    if (jsonElement!=null){
                        field.set(bean,jsonElement.getAsString());
                    }
                }else if (field.getGenericType().toString().contains("java.util.List")) {
                    JsonElement jsonElement=jsonObject.get(field.getName());
                    if (jsonElement!=null){
                        JsonArray jsonArray=jsonElement.getAsJsonArray();
                        String clazzName=getListClassName(field.getGenericType().toString());
                        field.set(bean,getListBean(clazzName,jsonArray));
                    }
                }else if (field.getGenericType().toString().contains("class ")){
                    //自定义bean泛型
                    String clazzName=getClassname(field.getGenericType().toString());
                    Object clazz=getClazz(clazzName);
                    JsonElement jsonElement=jsonObject.get(field.getName());
                    json2Bean(clazz,jsonElement.getAsJsonObject());
                    field.set(bean,clazz);
                }
            }
            return true;
        }catch (Exception e){
            logger.error("error",e);
            return false;
        }
    }


    /**
     * 依据list类名获取class名称
     * */
    public static String getListClassName(String clazzName){
        String[] a=clazzName.split("<");
        String[] b=a[1].split(">");
        String beanClazzname=b[0];
        return beanClazzname;
    }

    /**
     * 获取类名
     * */
    public static String getClassname(String clazzName){
        String[] a=clazzName.split("class ");
        return a[1];
    }

    /**
     * jsonArray转指定bean的list
     * */
    public static <T> List getListBean(String clazzName,JsonArray jsonArray){
        List list=new ArrayList<T>();
        for (JsonElement jsonElement:jsonArray){
            Object clazz=getClazz(clazzName);
            if (jsonElement.isJsonObject()){
                json2Bean(clazz,jsonElement.getAsJsonObject());
                list.add(clazz);
            }else if (jsonElement.isJsonPrimitive()){
                if (((JsonPrimitive) jsonElement).isString()){
                    list.add(jsonElement.getAsString());
                }else if (((JsonPrimitive) jsonElement).isBoolean()){
                    list.add(jsonElement.getAsBoolean());
                }else if (((JsonPrimitive) jsonElement).isNumber()){
                    if (clazzName.equals("int")){
                        list.add(jsonElement.getAsInt());
                    }else if (clazzName.equals("long")){
                        list.add(jsonElement.getAsLong());
                    }
                }
            }
        }
        return list;
    }

    /**
     * 通过类名获取类对象
     * */
    public static Object getClazz(String clazzName){
        try {
            return Class.forName(clazzName).newInstance();
        } catch (Exception e) {
            logger.error("error",e);
            return null;
        }
    }

    /**
     * gson bean转txt
     * */
    public static <T> String bean2gsonTxt( T bean,String clazzName){
        //processParam json转txt
        try {
            Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
            return gson.toJson(bean, Class.forName(clazzName));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            logger.error("error",e);
            return null;
        }
    }

    public static <T> JsonObject bean2gson( T bean,String clazzName){
        //processParam json转txt
        try {
            Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
            String txt= gson.toJson(bean, Class.forName(clazzName));
            JsonObject jsonObject =new Gson().fromJson(txt, JsonObject.class);
            return jsonObject;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            logger.error("error",e);
            return null;
        }
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class com.google.gson.FieldNamingStrategy.class com.google.gson.Gson.class com.google.gson.GsonBuilder.class com.google.gson.InstanceCreator.class com.google.gson.JsonArray.class com.google.gson.JsonDeserializationContext.class com.google.gson.JsonDeserializer.class com.google.gson.JsonElement.class com.google.gson.JsonIOException.class com.google.gson.JsonNull.class com.google.gson.JsonObject.class com.google.gson.JsonParseException.class com.google.gson.JsonParser.class com.google.gson.JsonPrimitive.class com.google.gson.JsonSerializationContext.class com.google.gson.JsonSerializer.class com.google.gson.JsonStreamParser.class com.google.gson.JsonSyntaxException.class com.google.gson.LongSerializationPolicy.class com.google.gson.TreeTypeAdapter.class com.google.gson.TypeAdapter.class com.google.gson.TypeAdapterFactory.class com.google.gson.annotations.Expose.class com.google.gson.annotations.SerializedName.class com.google.gson.annotations.Since.class com.google.gson.annotations.Until.class com.google.gson.internal.ConstructorConstructor.class com.google.gson.internal.Excluder.class com.google.gson.internal.JsonReaderInternalAccess.class com.google.gson.internal.LazilyParsedNumber.class com.google.gson.internal.LinkedTreeMap.class com.google.gson.internal.ObjectConstructor.class com.google.gson.internal.Primitives.class com.google.gson.internal.Streams.class com.google.gson.internal.UnsafeAllocator.class com.google.gson.internal.bind.ArrayTypeAdapter.class com.google.gson.internal.bind.CollectionTypeAdapterFactory.class com.google.gson.internal.bind.DateTypeAdapter.class com.google.gson.internal.bind.JsonTreeReader.class com.google.gson.internal.bind.JsonTreeWriter.class com.google.gson.internal.bind.MapTypeAdapterFactory.class com.google.gson.internal.bind.ObjectTypeAdapter.class com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.class com.google.gson.internal.bind.SqlDateTypeAdapter.class com.google.gson.internal.bind.TimeTypeAdapter.class com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.class com.google.gson.internal.bind.TypeAdapters.class com.google.gson.reflect.TypeToken.class com.google.gson.stream.JsonReader.class com.google.gson.stream.JsonScope.class com.google.gson.stream.JsonToken.class com.google.gson.stream.JsonWriter.class com.google.gson.stream.MalformedJsonException.class

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值