美文网首页
Java中将json映射到class

Java中将json映射到class

作者: caoxinyiyi | 来源:发表于2018-06-29 17:53 被阅读142次

    前言

    最近由于工作中项目的需要,需要在java端将json映射到class,现将整个过程总结一下。

    json数据结构

    [
      { "GoMethodName":"BasicTypeBool","GoInputParam":{"BasicType":{"boolParam":true}},"JavaReturnData":{"BasicType":{"boolParam":false}},
        "JavaMethodName":"testbool","JavaTypes":"boolean","ElemKey":"boolParam","JavaMapKey":"testbool","PtrFlag":false}
    ]
    
    

    java端class的定义

    由于json的层级分为了好几级,所以需要定义不同的class文件,具体实现的代码如下:

    DataParam.java
    
    package entity;
    public class DataParam {
        String GoMethodName;
        GoInputParam GoInputParam;
        JavaReturnData JavaReturnData;
        String JavaMethodName;
        String JavaTypes;
        String ElemKey;
        String JavaMapKey;   //需要将list转换成map所用到的key,跟每条数据关联
        boolean PtrFlag;
    }
    
    
    GoInputParam.java
    
    package entity;
    public class GoInputParam {
        BasicType  BasicType;
    }
    
    
    JavaReturnData.java
    
    package entity;
    
    public class JavaReturnData {
        BasicType  BasicType;
    }
    
    
    package entity;
    public class BasicType {
    
        boolean boolParam ;
    
        byte byteParam ;
    
        byte uint8Param;
    
        char charParam;
    
        short shortParam;
        
        int intParam ;
    
        long longParam;
        
        long long2Param;
        
        float floatParam;
    
        double doubleParam;
    
        String stringParam;
    }
    
    

    实现映射的具体逻辑

     //将json文件中的数据映射到DataParam实体类中
        import com.alibaba.fastjson.JSON;
    
        public static List<DataParam> getListDataFromJson(String jsonPath) {
            List<DataParam> ddps = new ArrayList<DataParam>();
            ddps = JSON.parseArray(readToString(jsonPath), DataParam.class);
    
            return ddps;
        }
    
     //将DataParam的list数据处理成map
        public static Map<String, DataParam> reverseListToMap(String jsonPath) {
            Map<String, DataParam> jsonToMapDatas = new HashMap<String, DataParam>();
           // for (int i = 0; i < 1; i++) {
                List<DataParam> res = getListDataFromJson(jsonPath);
                for (int j = 0; j < res.size(); j++) {
                    String mapKey = res.get(j).getJavaMapKey();
                    jsonToMapDatas.put(mapKey, res.get(j));
                }
           // }
            return jsonToMapDatas;
        }
    
    

    相关文章

      网友评论

          本文标题:Java中将json映射到class

          本文链接:https://www.haomeiwen.com/subject/aznayftx.html