gpt4 book ai didi

ios - 解析 json 获得的值是无序的

转载 作者:行者123 更新时间:2023-11-29 01:07:18 27 4
gpt4 key购买 nike

我有以下 json

{
"status": 1,
"value": {
"shipment_master": {
"1": "Order Placed",
"2": "In Production",
"3": "Quality Check In progress",
"4": "Goods received for shipment",
"5": "Stuffing in progress",
"6": "Cargo Shipped"
}
}
}

我将上面的json解析后添加到db中,如下所示,

  NSDictionary *valueDict = [jsonDic objectForKey:@"value"];
NSArray *details = [valueDict objectForKey:@"shipment_master"];

for (NSDictionary *response in details) {
NSManagedObjectContext *context = [self managedObjectContext];

// remove all rows

[context performBlockAndWait:^{
// add new row(s)
NSManagedObject *master = [NSEntityDescription insertNewObjectForEntityForName:@"ShipmentMaster" inManagedObjectContext:context];
NSError *error;

// TODO: set values here (e.g. [pendingShipment setValue:...)
[master setValue:[details valueForKey:response] forKey:@"values"];

// save MOC
if ([context hasChanges]) {
(void)[context save:&error];
}
}];
}

问题是,当我再次取回数据时,值的顺序与从服务器接收到的顺序不同。我的意思是 orderplacedin production 之后,quality check in prorgressinproduction 之后,依此类推。 ..但是当我获取数据时,数据是无序的。是因为 NSDictionary 在解析 json 时以无序方式获取值吗?还是有其他原因?

我尝试将 NSArray 更改为 NSDictionary 并将 valueForKey 更改为 objectForKey 但仍然存在相同的问题。

以下是我更新后的代码,

NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *valueDict = [jsonDic objectForKey:@"value"];
NSDictionary *details = [valueDict objectForKey:@"shipment_master"];

for (NSDictionary *response in details) {
NSManagedObjectContext *context = [self managedObjectContext];

// remove all rows

[context performBlockAndWait:^{
// add new row(s)
NSManagedObject *master = [NSEntityDescription insertNewObjectForEntityForName:@"ShipmentMaster" inManagedObjectContext:context];
NSError *error;

// TODO: set values here (e.g. [pendingShipment setValue:...)
[master setValue:[details objectForKey:response] forKey:@"values"];

// save MOC
if ([context hasChanges]) {
(void)[context save:&error];
}
}];
}

最佳答案

如果您希望数据以特定顺序返回,您需要在搜索谓词中指定该顺序。看起来您没有存储 ID,但如果顺序很重要,您将需要存储某种形式的索引。

let sortDescriptor = NSSortDescriptor(key: "id", ascending: true)
let sortDescriptors = [sortDescriptor]
request.sortDescriptors = sortDescriptors

关于ios - 解析 json 获得的值是无序的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36199256/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com