2013-07-05 82 views
2

我一直在嘗試創建一個類,允許我將核心數據輸出到JSON。NSJSONSerialization - 與JSON的核心數據關係

我設法得到它的工作到一個點,但我似乎已經撞了南牆上輸出關係

NSMutableArray * objectsArray = [[NSMutableArray alloc] init]; 

for (NSManagedObject * object in array) { 
    if([NSJSONSerialization isValidJSONObject:object]) { 
     [objectsArray addObject:object]; 
    } else { 

    NSMutableDictionary *fields = [NSMutableDictionary dictionary]; 
    for (NSAttributeDescription *attribute in [[object entity] properties]) { 
     NSString *attributeName = attribute.name; 
     id attributeValue = [object valueForKey:attributeName]; 

     if([results length] > 0) 
     { 
      NSArray *chunks2 = [results componentsSeparatedByString: @","]; 
      for (NSString * string in chunks2) { 
       if([string.lowercaseString isEqualToString:attributeName.lowercaseString]) 
       { 
        [fields setObject:[NSString stringWithFormat:@"%@",attributeValue] forKey:attributeName]; 
        break; 
       } 
      } 
     } 
     else 
     { 
      if (attributeValue) { 
       [fields setObject:[NSString stringWithFormat:@"%@",attributeValue] forKey:attributeName]; 
      } 
     } 
    } 
    [objectsArray addObject:fields]; 
    } 
} 

NSError *error; 
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:objectsArray options:kNilOptions error:&error]; 

而這個輸出數據精細aslong因爲我沒有例如關係一個 - >一對多或多對一 - >一個

它輸出以下

{ 
"mySegmentation": "(null)", 
"number": "9452062" 
}, 
{ 
"mySegmentation": "<NSManagedObject: 0x212050b0> (entity: SegmentationCodes; id: 0x212090b0 <x-coredata://BEC52F5F-EA26-4CFF-BCCB-09DA163F465D/SegmentationCodes/p13> ; data: <fault>)", 
"number": "9448502" 
}, 

我怎樣才能得到它也縮進和輸出從relationshi信息P +

我一直在抓我的頭在這一段時間,希望得到幫助

感謝馬特

回答

1

從文檔:

可以轉換成JSON對象必須具備以下屬性:

  • 頂層對象是NSArray或NSDictionary。
  • 所有對象都是NSString,NSNumber,NSArray, NSDictionary或NSNull的實例。
  • 所有的字典鍵都是NSString的實例。
  • 數字不是NaN或無窮大。

所以,你需要做的是組成一個字典或數組,字典,數組,字符串,數組,空值。

通常情況下,CoreData中的關係沒有排序,因此NSSets必須從集合中生成一個NSArray(因此Apple提供了一個很好的方法),並將其作爲特定鍵的字典中的值。

然後運行- dataWithJSONObject:options:error:(例如您之前所做的)並檢索正確的JSON。

不確定縮進是否正確。你必須檢查出來。

這就是它,希望