java 读取 json文件的两种方式

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 JSON_TEST;

    static {
        try {
            // 读取resources下的test.json文件
            JSON_TEST= (List) (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": "成功"
    }
}

 

方式二:

 

你可能感兴趣的:(●,Java)