• 使用fastjson取json字符串的值


    1、有以下格式的字符串

    {
      "status": 200,
      "message": "success",
      "data": {
        "result": {
          "cost": "1984ms",
          "total_size": 1,
          "file_list": [
            "userID",
            "userName",
            "userAge",
            "userEmail",
            "userCellPhone"
          ],
          "values": [
            [
              1,
              "張三",
              18,
              "13263254837@163.com",
              "13263254837"
            ],
            [
              2,
              "李四",
              34,
              "8753624@qq.com",
              "16358753624"
            ]
          ]
        }
      }
    }

    需求:取出所有的姓名。

    思路:获取file_list标签里userName的下标,通过下标取values 标签里的姓名

    实现:

    1、maven引入 fastjson jar包

            <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
            </dependency>

    2、代码实现:

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;

    import java.util.List;

    public class Test {
    public static void main(String[] args) {
    String result = "以上字符串";
    JSONObject jsonObject = JSON.parseObject(result);
    JSONArray keys = jsonObject.getJSONObject("data").getJSONObject("result").getJSONArray("file_list");
    List<JSONArray> values = JSON.parseArray(jsonObject.getJSONObject("data").getJSONObject("result").getString("values"), JSONArray.class);
    int keyIndex = keys.indexOf("userName");//需要脱敏的参数名称
    if (keyIndex > -1) {
    for (JSONArray valueArray : values) {
    String value = (String) valueArray.get(keyIndex);
    System.out.println("姓名:" + value);
    }
    }
    }
    }
  • 相关阅读:
    Java中OutOfMemoryError(内存溢出)的情况及解决办法
    php strtotime函数服务器和本地不相同
    Object传入String类型和其他
    Java静态变量,常量,成员变量,局部变量
    Vector使用
    Java反射机制
    List和ArrayList,LinkList的区别
    phpstrtotime()对于31日求上个月有问题
    PGsql解决时差24H
    drawable 另外一种形式dimens.xml
  • 原文地址:https://www.cnblogs.com/zhangjinmei/p/15509315.html
Copyright © 2020-2023  润新知