2013-09-16 57 views
8

tôi cố gắng để đọc một tệp JSON như thế này:Cách phân tích cú pháp JSONArray trong Java với Json.simple?

{ 
    "presentationName" : "Here some text", 
    "presentationAutor" : "Here some text", 
    "presentationSlides" : [ 
    { 
    "title" : "Here some text.", 
    "paragraphs" : [ 
    { 
     "value" : "Here some text." 
    }, 
    { 
     "value" : "Here some text." 
    } 
    ] 
    }, 
    { 
    "title" : "Here some text.", 
    "paragraphs" : [ 
    { 
     "value" : "Here some text.", 
     "image" : "Here some text." 
    }, 
    { 
     "value" : "Here some text." 
    }, 
    { 
     "value" : "Here some text." 
    } 
    ] 
    } 
    ] 
} 

Đó là một exercice trường, tôi chọn cách cố gắng sử dụng JSON.simple (từ GoogleCode) nhưng tôi mở cửa cho một thư viện JSON. Tôi nghe nói về Jackson và Gson: chúng tốt hơn JSON.simple?

Đây mã Java hiện tại của tôi:

 Object obj = parser.parse(new FileReader("file.json")); 

     JSONObject jsonObject = (JSONObject) obj; 

     // First I take the global data 
     String name = (String) jsonObject.get("presentationName"); 
     String autor = (String) jsonObject.get("presentationAutor"); 
     System.out.println("Name: "+name); 
     System.out.println("Autor: "+autor); 

     // Now we try to take the data from "presentationSlides" array 
     JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides"); 
     Iterator i = slideContent.iterator(); 

     while (i.hasNext()) { 
      System.out.println(i.next()); 
      // Here I try to take the title element from my slide but it doesn't work! 
      String title = (String) jsonObject.get("title"); 
      System.out.println(title); 
     } 

tôi kiểm tra rất nhiều ví dụ (một số trong Stack!) Nhưng tôi không bao giờ tìm thấy các giải pháp của vấn đề của tôi.

Có lẽ chúng ta không thể làm điều đó với JSON.simple? Bạn đề xuất món gì?

+0

Đây hoàn toàn là một cuộc tranh luận tôn giáo đối với tôi, nhưng tôi rất thích [Google GSON] (https://code.google.com/p/google-gson/) trên các trình phân tích cú pháp JSON khác. – david99world

+0

Thx để nhận xét. Nếu chương trình này hoạt động, tôi sẽ thử GSON sớm để đưa ra quyết định của riêng tôi! – Jibi

Trả lời

11

Bạn không bao giờ gán giá trị mới cho jsonObject, vì vậy bên trong vòng lặp nó vẫn đề cập đến đối tượng dữ liệu đầy đủ. Tôi nghĩ bạn muốn một cái gì đó như:

JSONObject slide = i.next(); 
String title = (String)slide.get("title"); 
+0

Tôi cố gắng và tôi sẽ sớm quay trở lại;) – Jibi

12

Nó hoạt động! Thx Russell. Tôi sẽ hoàn thành bài tập của mình và thử GSON để thấy sự khác biệt.

Code mới đây:

 JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides"); 
     Iterator i = slideContent.iterator(); 

     while (i.hasNext()) { 
      JSONObject slide = (JSONObject) i.next(); 
      String title = (String)slide.get("title"); 
      System.out.println(title); 
     } 
Các vấn đề liên quan