java后台读取json配置文件,返回json数据

后台开发的时候,有时候需要用json做一些假数据或者做一些配置。这个时候,怎么读取接送数据?我查了一些资料,最后我这样解决了。
json文件
json数据

{
  "resultCode":200,
  "code":200,
  "data":{
    "versionName":"1.2.0",
    "versionInfo":[
      "1.新版本信息......",
      "2.新版本信息......",
      "3.XUtil.getInstance().postJson(Urls.getWLJYList()......新版本信息新版本信息"
    ]
  }

}

json文件的工具类

package com.wdcloud.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdcloud.app.AppInterfaceMainpage;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class JsonResourceUtils {

    private static Logger logger = Logger.getLogger(JsonResourceUtils.class);

    private JsonResourceUtils() {

    }

    //filename 为文件名字 如 “/json/app_version_info.json”
    public static JSONObject getJsonObjFromResource(String filename) {
        JSONObject json = null;

        if (!filename.contains(".json")) {
            filename += ".json";
        }

        try {

            URL url = JsonResourceUtils.class.getResource(filename);
            String path = url.getPath();
            File file = new File(path);
            if (file.exists()) {
                String content = FileUtils.readFileToString(file, "UTF-8");
                json = JSON.parseObject(content);
            } else {
                logger.info("file not exist!");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("readFileToString" + e.getMessage());
        }


        return json;
    }
}

简单的使用


    //获取新版本的数据
    @RequestMapping(value = {"/getNewVersionInfo"}, method = {RequestMethod.POST})
    @ResponseBody
    public Object getNewVersionInfo(HttpServletRequest request, HttpServletResponse response) {
        logger.info("/getNewVersionInfo");

        return JsonResourceUtils.getJsonObjFromResource("/json/app_version_info.json");

    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值