[英]How to create a JSON object in objective-c?
我有如下所示的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;
因此,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
从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 *)数据选项:(NSJSONReadingOptions)选择错误:(NSError **)错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.