2013-02-26 21 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