2012-06-22 28 views
0

我想解析JSON數據。數據是一個包含對象的數組。 這是JSON數組我從網址獲得:iOS5:無法使用NSJSONSerialization從JSON讀取值

["{content:Airfare}", 
"{content:Dues \/ Subscriptions}", 
"{content:Education \/ Training}", 
"{content:Entertainment}", 
"{content:GS-OCWD}", 
"{content:GS-OCWE}", 
"{content:GS-Shift A}", 
"{content:GS-Shift B}", 
"{content:GS-Shift C}", 
"{content:Ground Transportation}", 
"{content:Legal Fees}", 
"{content:Lodging}", 
"{content:Meals}", 
"{content:Mileage}", 
"{content:Office Supplies}", 
"{content:Other Expenses}", 
"{content:Prof. Dues & Memberships}", 
"{content:Rental Car}", 
"{content:Telephone}", 
"{content:Telephone \/ Internet}", 
"{content:Tolls \/ Parking}"] 

當行NSLog(@"Item: %@", [item objectForKey:@"content"]);執行應用程序崩潰,這是一個用於解析JSON數組在我的.m文件

NSError *error = nil; 
    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost:8080/de.vogella.jersey.final/rest/notes"]];  


    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &error]; 

    if (!jsonArray) { 
     NSLog(@"Error parsing JSON: %@",error); 
    } else { 
     for(NSDictionary *item in jsonArray) { 
      NSLog(@"Item: %@", [item objectForKey:@"content"]); 
      [_identificationTypes1 addObject:item]; 
     } 

    } 

代碼給出[__NSCFString objectForKey:]: unrecognized selector錯誤。無法讀取關鍵內容。如果我將該行更改爲NSLog(@"Item: %@", item);,則可以看到所有值,如{content:Airfare}。我只需要機票價值。有人可以幫我

這是生成JSON的代碼。我正在使用Jersey和JAVA。 你能幫我使用URL中的JSON格式嗎?這是我的DAO代碼:

public JSONArray getAllNotes() 
    { 
     PreparedStatement prepStmt = null; 
     List<Note> notes = new ArrayList<Note>(); 
     try { 
      String cSQL = "SELECT EXPENDITURE_TYPE FROM PA_ONLINE_EXPENDITURE_TYPES_V; 
      prepStmt = connection.prepareStatement(cSQL); 
      ResultSet result = prepStmt.executeQuery(); 
      while (result.next()) 
      { 
       Note note = new Note(); 
       //note.setNoteId(result.getInt(1)); 
       note.setContent(result.getString(1)); 
       //note.setCreatedDate(new java.util.Date(result.getDate(3).getTime())); 
       notes.add(note); 
      } 
      return new JSONArray(notes); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
      prepStmt = null; 
      return null; 
     } 
    }      

這是POJO方法:

@Override 
     public String toString() { 
      //return "{Content:"+content+"}" ; 
      return "ExpType [content=" + content + "]"; 
     }  

這是調用DAO方法的方法:

@GET 

@Produces({MediaType.APPLICATION_JSON}) 
     public JSONArray getNotes() { 
      return dao.getAllNotes(); 
     }  

回答

0

你JSON是錯誤的。這只是一串字符串,這就是爲什麼你得到這個錯誤。它應該是什麼樣的:

[{"content":"Airfare"}, 
{"content":"Dues \/ Subscriptions"}, 
{"content":"Education \/ Training"}, 
... etc] 
+0

你如何創建正確的格式?你能幫我嗎我是新來的這 – user1342592

+0

我想說的是,問題是你從你的網址得到的迴應。在你的情況下,你從'http:// localhost:8080/de.vogella.jersey.final/rest/notes'得到的JSON格式是罪魁禍首。你的objc代碼沒有問題。 – Alladinian

+0

你能幫我使用URL中的JSON格式嗎?這是我的DAO代碼 – user1342592