2012-08-29 244 views
0

我具有以下JSON字符串 { 「PlayListName」: 「PlayList1」, 「CountOfFilesinPlayList」:5, 「PlayListArray」:[ { 「DEVID」:1,「FILEID 「:1,」Title「:」This is a test %% @ _1_1「,」m_iFileType「:0},{」DevId「:1,」FileId「:2,」Title「:」This is a test %% 「__1_2」,「m_iFileType」:1},{「DevId」:2,「FileId」:3,「Title」:「This is a test %% @ _2_3」,「m_iFileType」:0},{「DevId」 :2,「FileId」:4,「Title」:「This is a test %% @ _2_4」,「m_iFileType」:2},{「DevId」:3,「FileId」:5,「Title」:「This是一個測試%% @ _3_5" , 「文件類型」:0}]} 解析JSON陣列

雖然使用libJSON,我能夠得到的值: 「PlayListName」,「CountOfFilesinP layList「並且標識」PlayListArray「,我無法找到如何提取」PlayListArray「的內容。

以下是這是解析JSON字符串

int_n nCountOfFiles; 
PlayList_st *pPlaylistArr; 
int8_n szPlayListName[PLAYLIST_NAME_LENGTH]; 

json_object *new_obj; 
enum json_type type; 

new_obj = json_tokener_parse\ 
    ((char *)args[0].value.stringValue.UTF8Characters); 

if(!new_obj) { 
    result->type = NPVariantType_Bool; 
    result->value.boolValue = false; 
    return false; 
} 
json_object_object_foreach(new_obj, key, val) { 
    type = json_object_get_type(val); 
     switch(type) { 
     case json_type_int: 
      if(key && !strcmp((const char *)key, "CountOfFilesinPlayList")) 
      { 
       nCountOfFiles = json_object_get_int(val); 
       /* Allocate pPlaylistName array */ 
       if(nCountOfFiles > 0) 
       { 
        ..... 
        ..... 
       } 
       else 
       {     
        ..... 
        .....       
       } 
      } 
      break; 
     case json_type_string: 
      if(key && !strcmp((const char *)key, "PlayListName")) 
      {     
       strncpy (szPlayListName, json_object_get_string(val), \ 
        PLAYLIST_NAME_LENGTH-1); 

      } 
      break; 
     case json_type_array: 
      if(key && !strcmp((const char *)key, "PlayListArray")) 
      { 
       MEDIA_DEBUG_PRINT("\nwcf Media plugin: Found PlayListArray"); 
      } 
      break; 
     default: 
        result->type = NPVariantType_Bool; 
        result->value.boolValue = false; 
        return false;           
    } 
} 

回答

1

這應有助於代碼片段 - http://linuxprograms.wordpress.com/2010/06/01/json_object_get_array/ 您可以使用下面的代碼

json_object_object_foreach(jobj, key, val) { 
    type = json_object_get_type(val); 
    switch (type) { 
     case json_type_array: printf("type: json_type_array, "); 
          jobj = json_object_object_get(jobj, key); 
          int arraylen = json_object_array_length(jobj); 
          printf("Array Length: %dn",arraylen); 
          int i; 
          json_object * jvalue; 
          for (i=0; i< arraylen; i++){ 
          jvalue = json_object_array_get_idx(jobj, i); 
          printf("value[%d]: %sn",i, json_object_get_string(jvalue)); 
          } 
          break; 
    } 
    }