Java 阿里巴巴开源库FastJson

浏览 7 次     时间 2021-08-26 21:57:34     作者 有勇气的牛排    标签 Java

1 源数据

{
    "code":200,
    "msg":"success",
    "data":{
        "name":"导演",
        "age":20,
        "sex":"girl"
    }
}
{
    "code":200,
    "msg":"success",
    "data":[
         {
        "name":"导演",
        "age":20,
        "sex":"girl"
    },{
        "name":"灰太狼",
        "age":21,
        "sex":"boy"
    },{
        "name":"有勇气的牛排",
        "age":19,
        "sex":"girl"
    }
   ]
}

2 方案

2.1 maven 阿里 fastjson

  1. fastjson地址

  2. fastjson指南

  3. 安卓版本(未测)

    http://repo1.maven.org/maven2/com/alibaba/fastjson/1.1.51.android/
    
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>

2.1.1 解析JSON对象

String jsonData="{\n" +
                "    \"code\":200,\n" +
                "    \"msg\":\"success\",\n" +
                "    \"data\":{\n" +
                "        \"name\":\"导演\",\n" +
                "        \"age\":20,\n" +
                "        \"sex\":\"girl\"\n" +
                "    }\n" +
                "}";
//先把String对象转换成json对象
JSONObject object= JSONObject.parseObject(jsonData);

System.out.println(object.get("code"));
System.out.println(object.getJSONObject("data").get("name"));
System.out.println(object.getJSONObject("data").get("age"));
System.out.println(object.getJSONObject("data").get("sex"));

在这里插入图片描述

2.1.2 解析JSON对象数组

String jsonData="{\n" +
                "    \"code\":200,\n" +
                "    \"msg\":\"success\",\n" +
                "    \"data\":[\n" +
                "         {\n" +
                "        \"name\":\"导演\",\n" +
                "        \"age\":20,\n" +
                "        \"sex\":\"girl\"\n" +
                "    },{\n" +
                "        \"name\":\"灰太狼\",\n" +
                "        \"age\":21,\n" +
                "        \"sex\":\"boy\"\n" +
                "    },{\n" +
                "        \"name\":\"有勇气的牛排\",\n" +
                "        \"age\":19,\n" +
                "        \"sex\":\"girl\"\n" +
                "    }\n" +
                "   ]\n" +
                "}";
//先把String对象转换成json对象
JSONObject object= JSONObject.parseObject(jsonData);

List<HashMap> list =JSON.parseArray((object.get("data")).toString(), HashMap.class);
for(int i=0;i<list.size();i++){
    System.out.println(list.get(i).get("name"));;
}

在这里插入图片描述

参考文章 https://www.runoob.com/w3cnote/fastjson-intro.html https://qushen.blog.csdn.net/article/details/83515840

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。