How to store values of JSON in ARRAY/ String

本小妞迷上赌 提交于 2020-01-06 16:18:39

问题


I have the following JSON value:

-(
            { Key   = IsEmail;
              Value = 1;     },

            { Key   = TrackingInterval;
              Value = 20;    },

            { Key   = IsBackup;
              Value = 1;     },

            { Key   = WipeOnRestore;
              Value = 1;     }
)

How might I go about parsing this object into an array or string? - i.e. eack key values to be stored in an array and each Value to be stored in another array.

Please help me out with this.

Thanks :)


回答1:


This approach uses the json-framework.

I've shortened your example:

NSString *jsonString = @"[{\"Key\":\"IsEmail\",\"Value\":\"1\"},{\"Key\":\"TrackingInterval\",\"Value\":\"20\"},{\"Key\":\"IsBackup\",\"Value\":\"1\"}]";

NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];    

NSArray *json = [jsonString JSONValue];

for (NSDictionary *pair in json) {
    [keys addObject:[pair objectForKey:@"Key"]];
    [values addObject:[pair objectForKey:@"Value"]];        
}

NSLog(@"%@", keys); 
NSLog(@"%@", values);

Output:

2011-05-18 14:23:55.698 [36736:207] (
    IsEmail,
    TrackingInterval,
    IsBackup
)
2011-05-18 14:23:55.700 [36736:207] (
    1,
    20,
    1
)



回答2:


Refere

  • http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/

  • http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/

  • http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api/

  • http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c




回答3:


Your data is not vald json, You may want to structure it more like this:

var theObj = { IsEmail: 1, TrackingInterval: 20, IsBackup: 1, WipeOnRestore: 1 };

Then you could populate your key and value arrays something like this:

var keys = new Array();
var values = new Array();

for (prop in theObj) {
    keys.push(prop);
    values.push(theObj[prop]);
}



回答4:


if the JSON is in below format,

responseString=[ {
        Key = IsEmail;
        Value = 1;
    },
            {
        Key = TrackingInterval;
        Value = 20;
    },
            {
        Key = IsBackup;
        Value = 1;
    },
            {
        Key = WipeOnRestore;
        Value = 1;
    }] 

 then,

NSArray *resultArray=[responseSrting JSONValue];

NSMuatbleArray *keyArray=[[NSMutableArray alloc] init];

NSMutableArray *valueArray=[[NSMutableArray alloc] init];

for(NSDictionary *dict in resultsArray){

[keyArray addObject:[dict objectForKey:@"Key"]];

[valueArray addObject:[dict objectForKey:@"Value"]];

}

then, all your keys are stored in keyArray and all your values are stored in valueArray



来源:https://stackoverflow.com/questions/6044438/how-to-store-values-of-json-in-array-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!