2017-08-11 25 views
0

我遇到問題使用json-simple解析json對象數組。使用Json-simple從文件中解析對象數組

假設以下report對象數組:

[ 
    { 
    "title": "Test Object 1", 
    "description": "complicated description...", 
    "products": null, 
    "formats": ["csv"] 
    }, 
    { 
    "title": "Test Object 2", 
    "description": "foo bar baz", 
    "products": ["foo"], 
    "formats": ["csv", "pdf", "tsv", "txt", "xlsx"] 
    }, 
    { 
    "title": "Test Object 3", 
    "description": "Lorem Ipsum stuff...", 
    "products": null, 
    "formats": ["pdf", "xlsx"] 
    } 
] 

在下面的代碼,從文件中讀取在後,如何能遍歷每個對象陣列中執行的操作?

import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 

public class JsonReader { 

public static void main(String[] args) { 

    JSONParser parser = new JSONParser(); 

    try { 
     Object obj = parser.parse(new FileReader("sample.json")); 

     //convert object to JSONObject 
     JSONObject jsonObject = (JSONObject) obj; 

     //reading the string 
     String title = (String) jsonObject.get("title"); 
     String description = (String) jsonObject.get("description"); 

     //Reading an array 
     JSONArray products = (JSONArray) jsonObject.get("products"); 
     JSONArray formats = (JSONArray) jsonObject.get("formats"); 

     //Log values 
     System.out.println("title: " + title); 
     System.out.println("description: " + description); 

     if (products != null) { 
      for (Object product : products) { 
       System.out.println("\t" + product.toString()); 
      } 
     } else { 
      System.out.println("no products"); 
     } 

     if (formats != null) { 
      for (Object format : formats) { 
       System.out.println("\t" + format.toString()); 
      } 
     } else { 
      System.out.println("no formats"); 
     } 

    } catch (FileNotFoundException fe) { 
     fe.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

運行調試器,似乎jsonObject存儲數組,但我不知道如何去它。爲每個循環創建一個似乎不工作,因爲JSONObject不可迭代。

+0

看樣子你想要解析的JSON是一個JSONArray,而不是一個JSONObject。如果有幫助。 – drelliot

回答

2

我認爲您的JSON在JSON標準方面無效(請參閱JSON.org)。 JSON應以'{'開頭並以'}'結尾。我不認爲這個數組可以通過標準的方式訪問,因爲它缺少一個關鍵字。如果可能的話,你應該把與你的JSON(或只是CONCAT這在你的代碼的JSON字符串):

{ "array": 
    //yourJson 
} 

然後,你可以用類似acsess數組:

JSONArray array = (JSONArray) jsonObject.get("array"); 
Iterator iter = array.iterator(); 


while (iter.hasNext()) { 
     System.out.println((iter.next()).get("title")); 
    } 
相關問題