java读取json文件的函数

public 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;
	}
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestReadJson {
    public static void main(String[] args) {
    String JsonContext = new JsonUtil().ReadFile("E:\\ServerIPs.json");
        JSONArray jsonArray = JSONArray.fromObject(JsonContext);
        int size = jsonArray.size();
        for(int  i = 0; i < size; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONArray jsonArray2 = JSONArray.fromObject(jsonObject.getString("public").toString());
            int size1 = jsonArray2.size();
            for(int  j = 0; j < size1; j++){
                JSONObject jsonObject1 = jsonArray2.getJSONObject(j);
                if(jsonObject1.getInt("version")==4){
                    System.out.println("对外IPv4地址:"+jsonObject1.getString("addr"));
                }else{
                    System.out.println("对外IPv6地址:"+jsonObject1.getString("addr"));
                }
            }
        }
    }
}

json文件的内容:

[
{
        "public": [
            {
                "version": 4,
                "addr": "67.23.10.132"
            },
{
                "version": 6,
                "addr": "::babe:67.23.10.132"
            },
{
                "version": 4,
                "addr": "67.23.10.131"
            },
{
                "version": 6,
                "addr": "::babe:4317:0A83"
            }
        ],
        "private": [
            {
                "version": 4,
                "addr": "10.176.42.16"
            },
{
                "version": 6,
                "addr": "::babe:10.176.42.16"
            }
        ]
    }
]


你可能感兴趣的:(java读取json文件的函数)