gpt4 book ai didi

java - 当 JSON 为 null 时尝试从中提取

转载 作者:行者123 更新时间:2023-12-02 04:03:33 26 4
gpt4 key购买 nike

将尝试在这里解释我的问题。我有一个程序,应该解析我从网络爬虫收到的传入 JSON 文件。

    public static void Scan(Article article) throws Exception
{
//When running program, creates a error text-file inside java Project folder
File file = new File("errorlogg.txt");
FileWriter fileWriter = new FileWriter(file, true);

// if file doesn't exists, then create it
if (!file.exists())
{
file.createNewFile();
}

//Setting up an URL HttpURLConnection given DOI
URL urlDoi = new URL (article.GetElectronicEdition());

//Used for debugging
System.out.println("Initial DOI: " + urlDoi);

//Transform from URL to String
String doiCheck = urlDoi.toString();

//Redirect from IEEE Xplore toe IEEE Computer Society
if(doiCheck.startsWith("http://dx."))
{
doiCheck = doiCheck.replace("http://dx.doi.org/", "http://doi.ieeecomputersociety.org/");
urlDoi = new URL(doiCheck);
}

HttpURLConnection connDoi = (HttpURLConnection) urlDoi.openConnection();

// Make the logic below easier to detect redirections
connDoi.setInstanceFollowRedirects(false);

String doi = "{\"url\":\"" + connDoi.getHeaderField("Location") + "\",\"sessionid\":\"abc123\"}";

//Setting up an URL to translation-server
URL url = new URL("http://127.0.0.1:1969/web");
URLConnection conn = url.openConnection();

conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(doi);
writer.flush();

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));



while ((line = reader.readLine()) != null )
{
//Used to see of we get something from stream
System.out.println(line);

//Incoming is JSONArray, so create new array and parse fill it with incoming information
JSONArray jsonArr = new JSONArray(line);
JSONObject obj = jsonArr.getJSONObject(0);

//Check if names from DBLP is the same as translators get
//AuthorName, from field creators
JSONArray authorNames = obj.getJSONArray("creators");
ArrayList<Author> TranslationAuthors = new ArrayList<Author>();

这是我正在谈论的代码片段。正如你所看到的,当我从缓冲区读取器获得一些信息时,我想运行这段代码。我的问题是,当我没有获得有效的 JSON 时,我的程序似乎不会跳过。相反,它运行到这行代码:

        JSONArray authorNames = obj.getJSONArray("creators")

然后被迫退出,因为它无法获取“creators”字段,因为没有字段。我怎样才能确保我的程序不会遇到这个问题?我如何轻松地将其放入我创建的错误日志文件中,以至于我无法收集任何信息。

最佳答案

我认为您正在使用 org.json.JSONObject?如果是这样,则有一个 has 方法,可用于在 key 不存在时避免 JSONException

 JSONArray authorNames = null;
if (obj.has("creators")) {
authorNames = obj.getJSONArray("creators");
}

关于java - 当 JSON 为 null 时尝试从中提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34606711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com