Java解析json-简单应用

	package org.example;

	import com.alibaba.fastjson.JSONObject;

	import java.io.*;

	public class Main {
		public static void main(String[] args) {
			String filePath = "C:\\Users\\xxxx\\IdeaProjects\\test\\src\\main\\resources\\Sensor_to_iconpath.json";
			JSONObject jsonObejct = readJsonFile(filePath);

			String res = jsonObejct.get("1").toString();
			System.out.println("Hello world!:  "+res);
		}
		public static JSONObject readJsonFile(String filename){
			String jsonString = "";
			File jsonFile = new File(filename);
			try {
				FileReader fileReader = new FileReader(jsonFile);
				Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
				int ch = 0;
				StringBuffer stringBuffer = new StringBuffer();
				while ((ch = reader.read()) != -1){
					stringBuffer.append((char) ch);
				}
				fileReader.close();
				reader.close();
				jsonString = stringBuffer.toString();
			} catch (FileNotFoundException e){
				JSONObject notFoundJson = new JSONObject();
	//            notFoundJson.put("code",Code.GET_ERR);
				notFoundJson.put("msg","该Json文件不存在!");
				return notFoundJson;
			} catch (IOException e) {
				e.printStackTrace();
			}
			return JSONObject.parseObject(jsonString);
		}
	}

Java中JSON数据的读取和解析

posted @ 2023-03-23 16:23  badpear  阅读(28)  评论(0)    收藏  举报