将json转换为数据结构体

摘要:
主要用到的依赖:˂!

主要用到的依赖:(划重点:这个依赖需要加jdk版本号,不加的话用不了,且目前最高是jdk15)

(ps: 用于json与其他类型格式转换,JSONObject, JSONArray等来自这个包)

    <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>

核心代码:

packagecn.ucmed.pangu.lib;
importnet.sf.json.JSONArray;
importnet.sf.json.JSONObject;
importorg.apache.commons.collections.CollectionUtils;
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
public classConvertTool {
    public static List<BaseNode>analysisRequestJson(Object json) {
        List<BaseNode> baseNodeList = new ArrayList<>();
        NodeContainer nodeContainer = new NodeContainer(null, null, null, null);
        if (json instanceofJSONArray) {
            JSONArray jsonArray =(JSONArray) json;
            jsonArray.forEach(j ->analysisRequestJson(j));
        } else if (json instanceofJSONObject) {
            JSONObject jsonObject =(JSONObject) json;
            Iterator iterator =jsonObject.keys();
            while(iterator.hasNext()) {
                String key =iterator.next().toString();
                Object o =((JSONObject) json).get(key);
                if (o instanceofJSONArray) {
                    JSONArray jsonArray =(JSONArray) o;
                    analysisRequestJson(jsonArray);
                } else if (o instanceofJSONObject) {
                    List<BaseNode> list =analysisRequestJson((JSONObject) o);
                    nodeContainer = new NodeContainer(key, null, list);
                } else{
                    baseNodeList.add(new NodeLeafConstant(key, o.toString(), o.getClass().getTypeName().replace("java.lang.", "")));
                }
            }
            if(CollectionUtils.isNotEmpty(nodeContainer.nodeList)) {
                baseNodeList.add(nodeContainer);
            }
        }
        returnbaseNodeList;
    }
}

测试用例:

packagecn.ucmed.pangu.test;
importcn.ucmed.pangu.lib.ConvertTool;
importcn.ucmed.pangu.lib.NodeContainer;
importcn.ucmed.pangu.lib.NodeLeafConstant;
importnet.sf.json.JSONObject;
importorg.junit.Assert;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.springframework.test.context.junit4.SpringRunner;
importjava.util.ArrayList;
importjava.util.Arrays;
@RunWith(SpringRunner.class)
public classConvertToolTest {
    public static String jsonStr = "{
" +
            "    "app_id":"zsyy_android",
" +
            "    "app_key":"ZW5sNWVWOWhibVJ5YjJsaw==",
" +
            "    "coder":"enNseVpXNXNOV1ZXT1doaWJWSjVZakpzYXc9PQ",
" +
            "    "api_name":"api.nuts.invoker",
" +
            "    "data":{
" +
            "        "invoker_content":{
" +
            "            "apiId":"QueryDeptSchema",
" +
            "            "UseWay":"卓健",
" +
            "            "TransCode":"2004",
" +
            "            "UserId":"ZJYY",
" +
            "            "DeptCode":"1014",
" +
            "            "SeeDate":"2018-7-1",
" +
            "            "EndDate":"2018-7-5"
" +
            "        }
" +
            "    }
" +
            "}";
    public static NodeContainer expectedNodeContainer = new NodeContainer(new ArrayList<>(Arrays.asList(
            new NodeLeafConstant("app_id", "zsyy_android", "String"),
            new NodeLeafConstant("app_key", "ZW5sNWVWOWhibVJ5YjJsaw==", "String"),
            new NodeLeafConstant("coder", "enNseVpXNXNOV1ZXT1doaWJWSjVZakpzYXc9PQ", "String"),
            new NodeLeafConstant("api_name", "api.nuts.invoker", "String"),
            new NodeContainer("data", null, Arrays.asList(
                    new NodeContainer("invoker_content", null, Arrays.asList(
                            new NodeLeafConstant("apiId", "QueryDeptSchema", "String"),
                            new NodeLeafConstant("UseWay", "卓健", "String"),
                            new NodeLeafConstant("TransCode", "2004", "String"),
                            new NodeLeafConstant("UserId", "ZJYY", "String"),
                            new NodeLeafConstant("DeptCode", "1014", "String"),
                            new NodeLeafConstant("SeeDate", "2018-7-1", "String"),
                            new NodeLeafConstant("EndDate", "2018-7-5", "String")
                    ))
            ))
    )));
    @Test
    public voidtest() {
        JSONObject jsonObject =JSONObject.fromObject(jsonStr);
        NodeContainer requestNode = new NodeContainer(new ArrayList<>(ConvertTool.analysisRequestJson(jsonObject)));
        Assert.assertEquals(requestNode.toString(), expectedNodeContainer.toString());
    }
}

免责声明:文章转载自《将json转换为数据结构体》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Firefox显示中文字太小的问题 (改变Firefox最小字体) 拂晓风起iOS 16进制颜色的宏下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

java字符串与基础混淆

java字符串是一个类,是java虚拟机在启动的时候会实例化9个对象池,其中9个对象池分别用来存储8种基本数据类型(int,float,double,byte,boolean,short,long,char)的包装类和String对象。 Java String创建对象有两种方式,其中一种是通过直接创建:String str1="Stringhello",另...

Android学习——移植tr069程序到Android平台

原创作品,转载请注明出处,严禁非法转载。如有错误,请留言! email:40879506@qq.com 声明:本系列涉及的开源程序代码学习和研究,严禁用于商业目的。 如有任何问题,欢迎和我交流。(企鹅号:408797506)  淘宝店:https://shop484606081.taobao.com 本篇用到的代码下载路径:http://download....

response的响应头相关方法

响应头:Content-Type、Refresh、Location等等    头就是一个键值对!可能会存在一个头(一个名称,一个值),也可能会存在一个头(一个名称,多个值!)    > *****setHeader(String name, String value):适用于单值的响应头,例如:response.setHeader("aaa", "A...

JQuery几种动画效果的方法

下面介绍了几种动画效果的方法,具体如下: 1、show()显示效果 语法:show(speed,callback)  Number/String,Function speend为动画执行时间,单位为毫秒。也可以为slow","normal","fast" callback可选,为当动画完成时执行的函数。 show(speed,[easing],callba...

自己动手设计并实现一个linux嵌入式UI框架(设计)

  看了“自己动手设计并实现一个linux嵌入式UI框架”显然没有尽兴,因为还没有看到庐山真面目,那我今天继续,先来说说,我用到了哪些知识背景。如:C语言基础知识,尤其是指针、函数指针、内存分布,linux 基础知识、如消息队列、framebuffer、多线程、多线程同步、等,数据结构、算法(如链表、队列等),window .netframework 框架...

stringstream用法

分为istream和ostringstream. 1 std::string name("zeta");2 int age = 27;3 4 ostringstream os;5 os << "name:"<<name<<""<<"age:"<<age<<...