2013-02-26 25 views
-1

我有一個JavaScript DTO,如下所示。什麼是結構轉換爲json對象使用params =下面給出的DTO列表應該在這裏 in objective-c ??如何在objective-c中創建JSON對象?

我如何構建基於此的JSON對象?

private List<Long> sizes=new ArrayList<Long>(); 
private List<Long> colors=new ArrayList<Long>(); 
private List<Long> styles=new ArrayList<Long>(); 
private List<String> gender=new ArrayList<String>(); 
private List<Long> brands=new ArrayList<Long>(); 
private Long vendor; 
private String vendorName; 
private Boolean isNewArrival=false; 
private Boolean isSort=false; 
private Boolean isSale=false; 
private Boolean isNew=false; 
private Boolean isVintage=false; 
private Boolean isComingSoon=false; 
private Long saleSize; 
private Double minPrice=1.0; 
private Double maxPrice=5000.0; 
private Integer minSalePercentage=0; 
private Integer maxSalePercentage=70; 
private String socialCategory; 
+0

您的代碼例子是C#,它既不是Objective-C也不是Javascript。你嘗試了什麼?你能舉一個你試圖爲自己解決問題的例子嗎? – RyanR 2013-10-28 02:35:03

回答

3

所以DTO只是一種設計模式。 Read more

您可以創建一個具有相同屬性的類。

像:

//.h 
@interface SomeClassDTO : NSObject 
@property (nonatomic, strong) NSArray *sizes; 
@property (nonatomic, strong) NSArray *colors; 
... 
@property (nonatomic, assign) long vendor; 
... 
@end 

//.m 
@implementation SomeClassDTO 
@end 
1

從NSDictionary中創建的NSData:How can I convert NSDictionary to NSData and vice versa? 然後你就可以創建一個JSON對象,鏈接如下: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

創建基於您的DTO類,(我用本地變量)和 填充字典,然後使用NSJSONserialization方法 (具有所需的閱讀選項)來創建jSON對象。該 原油的例子是:

 NSArray *colorArray = [[NSArray alloc]initWithObjects:@"Blue",@"Gray",nil ]; 

     NSString *vendorName = @"Name"; 
     double minPrice = 800.0; 
     int minSalePercentage = 20;; 

     NSMutableDictionary *jSonDictionary = [[NSMutableDictionary alloc]init]; 

     //Convert primitive types to NSNumber 
     NSNumber *minPriceNum= [NSNumber numberWithDouble:minPrice]; 
     [jSonDictionary setObject:minPriceNum forKey:@"minPrice"]; 

     NSNumber *salePercentNum= [NSNumber numberWithInt:minSalePercentage]; 
     [jSonDictionary setObject:salePercentNum forKey:@"minSalePercentage"]; 

     [jSonDictionary setObject:vendorName forKey:@"vendorName"]; 
     [jSonDictionary setObject:colorArray forKey:@"colors"]; 

     //Convert the dictionary containing DTO values into NSData. 
     NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:jSonDictionary]; 

在此之後,你可以使用: +(ID)JSONObjectWithData:(NSData的*)數據選項:(NSJSONReadingOptions)選擇錯誤:(NSError **)錯誤

+0

我可以有一個示例代碼構建到json對象的DTO? – Preethi 2013-02-27 08:54:32