簡體   English   中英

嘗試從JSON為空時提取

[英]Trying to extract from JSON when it's null

將嘗試在這里解釋我的問題。 我有一個程序可以解析通過網絡爬蟲收到的傳入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>();

這是我正在談論的部分代碼。 如您所見,當我從bufferreader獲取一些信息時,我想運行此代碼。 我的問題是,當我沒有得到有效的JSON時,我的程序似乎沒有跳過。 而是運行到以下代碼行:

        JSONArray authorNames = obj.getJSONArray("creators")

然后由於沒有字段而無法獲得字段“創建者”,因此被迫退出。 如何確保我的程序不會遇到此問題? 如何將其輕松放入我創建的無法收集任何信息的錯誤日志文件中。

我認為您正在使用org.json.JSONObject嗎? 如果是這樣,則有一個has方法,可以在密鑰不存在的情況下避免JSONException

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM