首頁 > 軟體

java如何實現抽取json檔案指定欄位值

2022-06-16 10:02:06

使用場景

我有一個5000條資料的json檔案,每條資料包含地名、該地的經緯度等其他很多資訊。現在想把地名和經緯度抽出來匯入到資料庫中。

navicat自帶的匯入json格式檔案不好用,只能匯入json檔案中的外層資料,而我需要的地名和經緯度資訊在json的內層。

抽取json指定欄位值

json檔案格式

{
	"type": "FeatureCollection",
	"features": [{
			"type": "Feature",
			"geometry": {
				"type": "Point",
				"coordinates": [117.135437, 39.22393]
			},
			"properties": {
				"type": 1,
				"OBJECTID": 9288,
				"CC": "1117",
				"GB": "310107",
				"NAME": "某某村",
				"PAC": "120104008006111",
				"ELEMSTIME": "20150630",
				"ELEMETIME": "",
				"AREACODE": 120000,
				"FEATID": 120000403,
				"ChangeType": 0,
				"ChangeAtt": ""
			}
		},
		{
			"type": "Feature",
			"geometry": {
				"type": "Point",
				"coordinates": [117.17052343, 39.124663697000074]
			},
			"properties": {
				"OBJECTID": 9289,
				"CC": "1117",
				"GB": "310107",
				"NAME": "某某社群",
				"PAC": "120104003014111",
				"ELEMSTIME": "20150630",
				"ELEMETIME": "",
				"AREACODE": 120000,
				"FEATID": 120000458,
				"ChangeType": 0,
				"ChangeAtt": ""
			}
		}
	]
}

匯入依賴

在pom.xml檔案里加上fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.9</version>
</dependency>

程式碼實現

讀取本地json檔案的方法

public static String readJsonFile(String fileName) {
    String jsonStr = "";
    try {
        File jsonFile = new File(fileName);
        FileReader fileReader = new FileReader(jsonFile);
        Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        fileReader.close();
        reader.close();
        jsonStr = sb.toString();
        return jsonStr;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

讀取指定欄位

先把json檔案放在resourses下面(直接複製到resourses)

String path = ddem.class.getClassLoader().getResource("villagePoint.json").getPath();
String s = readJsonFile(path);
JSONObject jobj = JSON.parseObject(s);
JSONArray features = jobj.getJSONArray("features");//構建JSONArray陣列
for (int i = 0; i < features.size(); i++) {
    JSONObject key = (JSONObject) features.get(i);
    JSONObject geometry =key.getJSONObject("geometry");
    JSONArray coordinates=geometry.getJSONArray("coordinates");
    BigDecimal jingdu = coordinates.getBigDecimal(0);
    BigDecimal weidu = coordinates.getBigDecimal(1);
    JSONObject properties=key.getJSONObject("properties");
    String name =(String)properties.getString("NAME");
//          System.out.println(jingdu);
//          System.out.println(weidu);
    System.out.println(name);
}

JSONObject或JSONArray可以get很多種型別,具體用哪個看你自己的json內容

完整程式碼

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.math.BigDecimal;
public class ddem {
    public static void main(String[] args) {
        String path = ddem.class.getClassLoader().getResource("villagePoint.json").getPath();
        String s = readJsonFile(path);
        JSONObject jobj = JSON.parseObject(s);
        JSONArray features = jobj.getJSONArray("features");//構建JSONArray陣列
        for (int i = 0; i < features.size(); i++) {
            JSONObject key = (JSONObject) features.get(i);
            JSONObject geometry =key.getJSONObject("geometry");
            JSONArray coordinates=geometry.getJSONArray("coordinates");
            BigDecimal jingdu = coordinates.getBigDecimal(0);
            BigDecimal weidu = coordinates.getBigDecimal(1);
            JSONObject properties=key.getJSONObject("properties");
            String name =(String)properties.getString("NAME");
//          System.out.println(jingdu);
//          System.out.println(weidu);
            System.out.println(name);
        }
    }
    //讀取json檔案
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

把需要的資料整理到excel中

如上例所示,我需要地名和經緯度,可以一次性查出三列資料,但是為了複製到excel比較方便,我選擇一個一個查出來,逐個複製到excel中,再為每列起個列名,就能非常方便地使用navicat的”匯入xls“功能匯入大量資料啦~

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com