如何为 JSON 字符串赋值?

How assign value to a JSON string?

我从我的 Web 服务中获取这个 JSON 对象

0:  {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}

当我尝试为用户名 JSON 字符串赋值时,出现语义错误:

id obj = [NSJSONSerialization JSONObjectWithData:data
                                                 options:NSJSONReadingAllowFragments
                                                   error:&error];
            for (NSDictionary *dictionary in array) {
                NSString *usernameString = @"";
//this line of code gives me an error: Expression is not assignable               
[dictionary objectForKey:@"Username"] = usernameString   ;

我知道如何使用 NSJSON 序列化 class 获取 JSON 对象,但我的目标是如何将值 @"" 赋给 JSON 对象。 那么如何将值 @"" 分配给用户名 JSON 字符串?

你的赋值操作写错了,确实应该是这样的:

  • 如果需要从字典中获取值

    usernameString = [dictionary objectForKey:@"Username"];
    
  • 如果你想给你的字典设置一个值,首先你的字典应该是NSMutableDictionary

    [dictionary setObject:usernameString forKey:@"Username"];
    
 NSData *data = [NSData dataWithContentsOfURL:url];
        NSError *error;
        id obj = [NSJSONSerialization JSONObjectWithData:data
                                                 options:NSJSONReadingAllowFragments
                                                   error:&error];

        if(!error && [obj isKindOfClass:[NSArray class]]){
            NSArray *array = (NSArray *)obj;
            Booking *booking = nil;
            for (NSMutableDictionary *dictionary in array) {
               NSString *usernameString = @"";
//this line of code gives me an error: Expression is not assignable               
[dictionary objectForKey:@"Username"] = usernameString;

是的,是编译器错误

当您尝试从 array 获取 dictionary 时。它不是可变字典,因此您需要在从 Array 获取数据时创建 NSMutableDictionary。以下代码将帮助您更改 username.

for (NSMutableDictionary *dictionary in array)
{
   NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];

   [dictTemp setObject:usernameString forKey@"Username"];

   [_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}

您需要有一个可变字典才能更改值。试试这个

for (NSDictionary *dictionary in array) {
   NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
   NSString *usernameString = @"";     
   [mutableDictionary setValue:@"" forKey:usernameString];
}       

即使答案都是正确的,我想补充一点,您不必自己做。 NSJSONSerialization 已经有了解决方案。只需将其中之一作为选项传递:

NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),

阅读 JSON 时。