java 读取 json文件的两种方式

Duang,最近搭建了一个自己的博客小破站,欢迎各位小伙伴来访吖:

ares-coder-blog-portalhttps://www.ares-stack.cn/blog_service/#/game

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": "成功"
    }
}

方式二:

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值