java 读取 json文件的两种方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_41888813/article/details/90757259

resource下的json文件 

[
  {
    "type": 1,
    "sites": {
      "site": [
        {
          "id": "1",
          "name": "one"
        },
        {
          "id": "2",
          "name": "two"
        }
      ]
    }
  },
  {
    "type": 2,
    "sites": {
      "site": [
        {
          "id": "3",
          "name": "three"
        },
        {
          "id": "4",
          "name": "four"
        }
      ]
    }
  }
]

方式一:

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

@Mapping(value = "/test")
public class TestController extends Controller {

    private final static List<JSONObject> JSON_TEST;

    static {
        try {
            // 读取resources下的test.json文件
            JSON_TEST= (List<JSONObject>) (List<?>)JSON.parseArray(IOUtils.toString(
                    new FileInputStream(new File(getProjectRootPath() + "/WEB-INF/classes/test.json")), Charsets.UTF_8.toString()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public void getSitesByType() {
        for (JSONObject json: SPORT_CONFIG) {
            // 取出type为2的stites
            if (json.getIntValue("type") == 2) {
                this.returnSuccessJson(ExceptionEnums.SUCCESS, json.get("sites"));
            }
        }
    }

    /**
     * 获取项目根路径
     */
    public static String getProjectRootPath() {
        String result = null;
        try {
            result = new File(ToolsKit.class.getResource("/").toURI().getPath()).getParentFile()
                    .getParentFile().getCanonicalPath();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (StringUtils.isNotEmpty(result)) {
            return result;
        } else {
            throw new RuntimeException("未找到项目根路径");
        }
    }

}

 result

{
    "data": {
        "site": [
            {
                "id": "3",
                "name": "three"
            },
            {
                "id": "4",
                "name": "four"
            }
        ]
    },
    "head": {
        "clientId": "localhost:8089",
        "method": "GET",
        "msg": "成功"
    }
}

 

方式二:

 

展开阅读全文

没有更多推荐了,返回首页