我从我的网络服务中获取此JSON对象
0: {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}
当我尝试将值分配给Username 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 ;
我知道如何使用NSJSONSerialization类获取JSON对象,但我的目标是如何将值@“”分配给JSON对象。 那么如何将值@“”分配给Username JSON字符串?
答案 0 :(得分:1)
当您尝试从dictionary
抓取array
时。它不是可变字典,因此您需要在从NSMutableDictionary
获取数据时创建Array
。以下代码可帮助您更改username
。
for (NSMutableDictionary *dictionary in array)
{
NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[dictTemp setObject:usernameString forKey@"Username"];
[_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}
答案 1 :(得分:0)
你的作业操作写错了,应该是这样的:
如果你需要从字典中获取价值
usernameString = [dictionary objectForKey:@"Username"];
如果您想为字典设置一个值,首先您的字典应为NSMutableDictionary
[dictionary setObject:usernameString forKey:@"Username"];
答案 2 :(得分:0)
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;
是的,是编译错误
答案 3 :(得分:0)
您需要有一个可变字典才能更改该值。试试这个
for (NSDictionary *dictionary in array) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
NSString *usernameString = @"";
[mutableDictionary setValue:@"" forKey:usernameString];
}
答案 4 :(得分:0)
即使答案是正确的,我想补充一点,你不必自己动手。 NSJSONSerialization
已经有了解决方法。只需传递以下选项之一:
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
阅读JSON时。