簡體   English   中英

如何在Objective-C中創建JSON對象?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM