-1

我有一个 javascript DTO,如下所示。使用下面给出的 params=DTO 列表转换为 json 对象的结构应该在 Objective-c 中出现吗?

如何基于此构造 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; 
4

2 回答 2

3

所以DTO只是一种设计模式而已。阅读更多

您可以创建一个具有相同属性的类。

喜欢:

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

//.m
@implementation SomeClassDTO
@end
于 2013-02-26T16:26:27.770 回答
1

从 NSDictionary 创建 NSData:如何将 NSDictionary 转换为 NSData,反之亦然? 然后你可以创建一个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 *)data options:(NSJSONReadingOptions)opt error:(NSError **)error

于 2013-02-27T08:45:10.580 回答