解决FastJson-com-alibaba-fastjson-JSONObject-cannot-be-cast-to的问题

1.问题

在读取json文件,返回页面json串时,发生如下错误

java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject

2.排查

2.1 code review

读取JSON文件转换成string的方法

	public static String ReadFile(String Path) {

		BufferedReader reader = null;

		String laststr = "";
		try {
			FileInputStream fileInputStream = new FileInputStream(Path);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				laststr += tempString;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return laststr;
	}

调用类

	@RequestMapping(value = "menu")
	@ResponseBody
	public JSONObject menu(String id) {
		String url = HttpContext.current().getRequest().getServletContext().getRealPath("/");
		if (id.equals("1")) {
			url = url + "/static/json/images.json";
		} else if (id.equals("2")) {
			url = url + "/static/json/linksList.json";
		} 
		String output = FileUtils.ReadFile(url);
		System.out.println(output);
		JSONObject JSONObject =  JSON.parseObject(output);
		return JSONObject;
	}

2.2 错误点

#工具类返回的是属于string类型,而不是JSONARRAY

3.解决

	String output = FileUtils.ReadFile(url);
	System.out.println(output);
	JSONArray jsonArray =  JSONObject.parseArray(output);
	return jsonArray;

使用***JSONObject.parseArray(output)***方法,将string转化为JSONAarray。

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://blog.wyatt.plus/?p=44

Buy me a cup of coffee ☕.