我希望以递归方式读取下面内容的json文件。我该如何实现?
{"preview":false,"result":{"TransactionType":"Mobile","TransactionID":"STSVSTFS7SVS3S","TransTime":"20181210171511"}}
{"preview":false,"result":{"TransactionType":"Mobile","TransactionID":"LKSNS6S2S7SVS3S","TransTime":"20181210171511"}}
{"preview":false,"result":{"TransactionType":"Mobile","TransactionID":"TSSKBDGD7SVS3S","TransTime":"20181210171511"}}
这是我的Java代码,除了它只读取第一个json
import com.brian.db.DBConnector;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJSONData {
private static final String filePath = "D:\\test\\c2b.json";
public static void main(String[] args) throws SQLException {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
//System.out.println(jsonObject);
Object preview = jsonObject.get("preview");
System.out.println("Preview:"+preview);
JSONObject result = (JSONObject) jsonObject.get("result");
System.out.println("RESULT:"+result);
String transactionType = (String) result.get("TransactionType");
System.out.println("TransactionType:"+transactionType);
String transid = (String) result.get("TransID");
System.out.println("TransID:"+transid);
String transTime = (String) result.get("TransTime");
System.out.println("TransTime:"+ transTime);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
答案 0 :(得分:1)
iterate over the lines和parse each one separately:
public class ReadJSONData {
private static final String filePath = "D:\\test\\c2b.json";
public static void main(String[] args) throws SQLException {
JSONParser jsonParser = new JSONParser();
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.forEach(line -> {
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
…
} catch (Exception e) {
}
});
}
}
}