利用org.json即可实现
1. 基本的な考え方
まず IO ストリームを使用して txt ファイルを読み取り、各行の内容を読み取り、通常の文字列に変換します (json フォームの形式が正しい必要があります)。次に、それを JSONObject オブジェクトに変換し、JSONObject オブジェクトを使用します。さまざまな種類の値を取得します。
txt ファイルのコンテンツ形式は次のとおりです。
2、特定のコード
コードは次のとおりです(例)。
public static void main(String[] args) throws IOException {
String jsonpath="E:\\河南省乡镇点\\12.txt";
ReadGeojson.ReadGeojsonFile(jsonpath);
}
public static void ReadGeojsonFile(String jsonpath) throws IOException {
//读取txt文件流
File file=new File(jsonpath);
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
BufferedReader bufReader = new BufferedReader(inputStreamReader);
try {
String line="";
//读取每行内容
StringBuffer sb=new StringBuffer();
while ((line=bufReader.readLine())!=null){
sb.append(line);
}
//去除空格
String sbreplace = sb.toString().replace(" ", "");
System.out.println(sbreplace);
//转换成为JSONObject对象
JSONObject jsonObj =new JSONObject(sbreplace);
System.out.println(jsonObj.get("dataType"));
//第二层
Object attributes = jsonObj.get("attributes");
System.out.println(attributes);
JSONObject attributesObj =new JSONObject(attributes.toString());
System.out.println(attributesObj.get("userId"));
//数组形式
JSONArray geometry =(JSONArray) jsonObj.get("geometry");
System.out.println(geometry.get(0));
System.out.println(geometry.toString());
} catch (IOException e) {
e.printStackTrace();
}
bufReader.close();
}
結果は次のとおりです
要約する
txt ファイルの形式が json 形式の要件を満たしていない場合、JSONObject jsonObj =new JSONObject(sbreplace); でエラーが発生します。この手順は通常、JSONObject テキストは 1 [character 2 line 1] の '{' で始まる必要があります。 』など。