2017-07-24 177 views
0

下面我附加了Java代碼,首先我要檢索「圖片」結果爲「{」jpg「:」JPEG文件「,」gif「:」GIF文件「,」png「 :「使用得到的,試圖讓檢索JSON對象

‘JPG’節點,無法檢索數據「PNG文件」},而不是我得到錯誤的java.lang.String cannot be cast to org.json.simple.JSONObject

我喜歡拍攝的圖像和接着是jpg。不能直接JPG值

import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 

    public class JSONDemo { 

     public static void main(String[] args) { 
      try{ 
      String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}"; 
      JSONObject jobject=new JSONObject(); 
      JSONParser jparser=new JSONParser(); 
      jobject = (JSONObject) jparser.parse(jsonfile); 
      jobject=(JSONObject) jobject.get("images"); 
      System.out.println(jobject); 
      System.out.println(jobject.getClass().getName()); 

      jobject=(JSONObject) jobject.get("jpg"); 
      }catch(Exception e){ 
       System.out.println(e.getMessage()); 
      } 
     } 
    } 

回答

0

你這裏的錯誤是「JPG」不是JSONObject,但與關聯值"JPEG file"這是一個簡單的字符串的關鍵。這就是爲什麼你會收到這樣的錯誤。

在ordre中檢索與密鑰jpg關聯的值,請閱讀下面的代碼。我添加了一些評論以幫助您瞭解每個步驟,但可隨時索取更多詳細信息。

String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}"; 

    JSONObject jobject = new JSONObject(); 
    JSONParser jparser = new JSONParser(); 

    //Convert your string jsonfile into a JSONObject 
    try { 
     jobject = (JSONObject) jparser.parse(jsonfile); 
    } catch (ParseException ex) { 
     Logger.getLogger(Josimarleewords.class.getName()).log(Level.SEVERE, null, ex); 
    } 

    System.out.println(jobject.toString());  
    //{"Address":"Chennai","name":"Raj","images":{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"}} 

    //Get the node image, and convert it into a JSONObject 
    //You're able to do so, because the value associated to "images" 
    //is in json format. 
    jobject=(JSONObject) jobject.get("images"); 
    System.out.println(jobject.toString()); 
    //{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"} 

    //Retrieves the value associated to the key jpg. 
    //The value here is not in json format, it is a simple string 
    String jpg = (String)jobject.get("jpg");     
    System.out.println(jpg.toString()); 
    //JPEG file 
+0

謝謝,現在我明白了...... –

+0

不要忘記通過驗證答案來解決問題。 – Asew

+0

如何標記解決? Asew –