How can I parse a file of this kind:
{"group":"1"}{"group":"2"}{"group":"3"}
Usually I parse in this way:
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:reloadPath];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
// getting the data from inside of "menu"
//NSString *message = (NSString *) [data objectForKey:#"message"];
//NSString *name = (NSString *) [data objectForKey:#"name"];
NSArray *messagearray = [data objectForKey:#"message"];
NSArray *namearray = [data objectForKey:#"name"];
NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:messagearray forKeys:namearray];
...objects of this king...
{"message":["Besth"],"name":["thgh"]}
...but in the type I want to parse, which is the key and object??
By the way I want to retrieve a list like this: 1, 2, 3, ...
This is not valid JSON. You can validate for example at: http://jsonlint.com
You could rewrite it as valid JSON like so:
{
"some_groups": [
{
"group": "1"
},
{
"group": "2"
},
{
"group": "3"
}
]
}
Then you could extract the data by doing something like this:
NSArray *groups = [data objectForKey:#"some_groups"];
for (NSDictionary *group in groups) {
NSLog(#"group number: %#", [group valueForKey:#"group"]);
}
Related
i tried to create static JSONArray of value in IOS using Objective -c
i want like this
tabledata={
["name":"image 1","path":"img1.jpg"],
["name":"image 2","path":"img2.jpg"],
["name":"image 3","path":"img3.jpg"],
["name":"image 4","path":"img4.jpg"],
["name":"image 5","path":"img5.jpg"],
["name":"image 6","path":"img6.jpg"],
["name":"image 7","path":"img7.jpg"]}
this is my data.. please help me any one how can i declare in objective-c..
You can create dictionary like below
NSDictionary *dict = #{
#"array": #[
#{
#"name":#"image 1",
#"path":#"img1.jpg"
},
#{
#"name":#"image 2",
#"path":#"img2.jpg"
}
....
]
};
and Array
NSArray *array = #[
#{
#"name":#"image 1",
#"path":#"img1.jpg"
},
#{
#"name":#"image 2",
#"path":#"img2.jpg"
}
....
];
For get value from NSDictionary
NSArray *array = NSDictionary[#"array"]
NSDictionary *firstObj = array[0];
NSString *name = firstObj[#"name"]
NSString *path = firstObj[#"path"]
from Array just
NSDictionary *firstObj = array[0];
NSString *name = firstObj[#"name"]
NSString *path = firstObj[#"path"]
One of the alternative old approach is:
NSMutableArray *tableData = [[NSMutableArray alloc] init];
NSMutableDictionary * dict1 = [[NSMutableDictionary alloc] init];
[dict1 setValue:#"image 1" forKey:#"name"];
[dict1 setValue:#"img1.jpg" forKey:#"path"];
NSMutableDictionary * dict2 = [[NSMutableDictionary alloc] init];
[dict2 setValue:#"image 2" forKey:#"name"];
[dict2 setValue:#"img2.jpg" forKey:#"path"];
NSMutableDictionary * dict3 = [[NSMutableDictionary alloc] init];
[dict3 setValue:#"image 3" forKey:#"name"];
[dict3 setValue:#"img3.jpg" forKey:#"path"];
[tableData addObject:dict1];
[tableData addObject:dict2];
[tableData addObject:dict3];
NSLog(#"%#",tableData);
//To Fetch Values
NSDictionary *dictionary1 = [tableData objectAtIndex:0];
NSLog(#"%#", [dictionary1 valueForKey:#"name"]);
You can make JsonString to NSDicitonary.
NSError *jsonError;
NSData *objectData = [#"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
and It is make NSDictionary with array.
- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
id objectInstance;
NSUInteger indexKey = 0U;
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
for (objectInstance in array)
[mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];
return (NSDictionary *)[mutableDictionary autorelease];
}
I am using an API to convert Json Data into Object data,
please visit the API I am using
Please Visit the API page which I am using
Here is the snap of my code with highlighted issues
Issues
and here is the raw code
-(void) retrieveData{
NSURL * url = [NSURLURLWithString:getDataUrl];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
NSLog(#"JsonArray %#", jsonArray);
//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];
//Loop through our jsonArray
for (int i = 0; i<jsonArray.count; i++)
{
NSString * yId = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"id"];
// NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:#"id"];
NSString * yName = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"name"];
NSString * yDescription = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"description"];
NSString * yImage = [[[[jsonArray objectAtIndex:i]objectForKey:#"data"]objectAtIndex:#"categories"]objectForKey:#"image"];
//Add the city object to our citiesArray
[yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];
}
Thanks #Lame, I followed your code, as it was giving me 6 to 8 errors, but I understand your code & configured error in that now here is the complete solution which works according to my requirements or (perfect answer according to my asked question)
-(void) retrieveData{
NSURL * url = [NSURL URLWithString:getDataUrl];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *dataJSON = [jsonDict objectForKey:#"data"];
NSArray *allCategoriesJSON = [dataJSON objectForKey:#"categories"];
yougaArray = [[NSMutableArray alloc] init];
for (int i = 0; i < allCategoriesJSON.count; i ++)
{
NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
NSString *yId = [aCategoryJSON objectForKey:#"id"];
NSString *yName = [aCategoryJSON objectForKey:#"name"];
NSString *yDescription = [aCategoryJSON objectForKey:#"description"];
NSString *yImage = [aCategoryJSON objectForKey:#"image"];
[yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];
According to your JSON response its a Dictionary type object not an array so your code should be like this,
NSMutableDictionary *dictData = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
NSLog(#"JsonArray %#", dictData);
NSArray *jsonArray=[[dictData objectForKey:#"data"] objectForKey:#"categories"];
//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];
for (int i = 0; i<jsonArray.count; i++)
{
NSString * yId = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
// NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:#"id"];
NSString * yName = [[jsonArray objectAtIndex:i] objectForKey:#"name"];
NSString * yDescription = [[jsonArray objectAtIndex:i] objectForKey:#"description"];
NSString * yImage = [[jsonArray objectAtIndex:i] objectForKey:#"image"];
//Add the city object to our citiesArray
[yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];
Hope it works for you. Let me know!!
Happy coding. :)
You JSON seems like this :
{
"meta": {
"status": "200",
"msg": "OK"
},
"data": {
"total_pages": 0,
"total_categories": 2,
"current_page": 1,
"next_page": 0,
"categories": [{
"id": "2",
"name": "Articles",
"description": "Yoga Articles",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}, {
"id": "1",
"name": "Poses",
"description": "Yoga Poses",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}]
}
}
now replace your existing code with the code below:
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];
NSLog(#"JsonArray %#", jsonArray);
//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];
//Loop through our jsonArray
NSArray *dataArray = [[jsonArray objectForKey#"data"] objectForKey:#"categories"];
for (int i = 0; i < dataArray.count; i++) {
NSString * yId = [[dataArray objectAtIndex:i] objectForKey:#"id"];
NSString * yName = [[dataArray objectAtIndex:i] objectForKey:#"name"];
NSString * yDescription = [[dataArray objectAtIndex:i] objectForKey:#"description"];
NSString * yImage = [[dataArray objectAtIndex:i] objectForKey:#"image"];
//Add the city object to our citiesArray
[yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
[self.tableView reloadData];
Let me know if the solution works for you, also if anything comes up.
This is the JSON:
{
"meta": {
"status": "200",
"msg": "OK"
},
"data": {
"total_pages": 0,
"total_categories": 2,
"current_page": 1,
"next_page": 0,
"categories": [{
"id": "2",
"name": "Articles",
"description": "Yoga Articles",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}, {
"id": "1",
"name": "Poses",
"description": "Yoga Poses",
"image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
}]
}
}
Your JSON is a NSDictionary at top level! Not a NSArray!
Also, avoid doing all objectForKey:/objectAtIndex: in the same line/instruction, it's harder to read, but also harder to debug, especially when you don't know what you are doing.
Also, when there is an error parameter, use it, don't put nil.
So:
NSError *errorJSON = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJSON];
if (errorJSON)
{
NSLog(#"ErrorJSON: %#", errorJSON);
return;
}
NSDictionary *dataJSON = [jsonDict objectForKey:#"data"];
NSArray *allCategoriesJSON = [dataJSON objectForKey:#"categories"];
for (NSUIInteger i = 0; i < allCategoriesJSON.count; i ++)
{
NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
NSString yID = [aCategoryJSON objectForKey:#"id"];
NSString yName = [aCategoryJSON objectForKey:#"name"];
NSString yDescription = [aCategoryJSON objectForKey:#"description"];
NSString yImage = [aCategoryJSON objectForKey:#"image"];
[yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}
Im having hard time while trying to parse the following json array. How to parse it. The other answers in web doesn't seem to solve my problem.
{
"status": 1,
"value": {
"details": [
{
"shipment_ref_no": "32",
"point_of_contact": {
"empid": ""
},
"products": {
"0": " Pizza"
},"status": "2"
},
{
"shipment_ref_no": "VAPL/EXP/46/14-15",
"point_of_contact": {
"empid": "60162000009888"
},
"products": {
"0": "MAIZE/CORN STARCH"
},
"status": "5"
}
]
}
}
I have to access the values of each of those keys.
Following is my code
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
This is how you can parse your whole dictionary:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *details = [[dataDictionary objectForKey:#"value"] objectForKey:#"details"];
for (NSDictionary *dic in details) {
NSString *shipmentRefNo = dic[#"shipment_ref_no"];
NSDictionary *pointOfContact = dic[#"point_of_contact"];
NSString *empId = pointOfContact[#"empid"];
NSDictionary *products = dic[#"products"];
NSString *zero = products[#"0"];
NSString *status = dic[#"status"];
}
NSString *pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
//argsArray holds objects in form of NSDictionary.
for(NSDictionary *response in argsArray) {
//String object
NSLog(#"%#", [response valueForKey:#"shipment_ref_no"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"point_of_contact"] valueForKey:#"empid"]);
//String object
NSLog(#"%#", [response valueForKey:#"status"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"products"] valueForKey:#"0"]);
}
I believe you should surely ask your server developer to update the response format.
Also, you can always use Model classes to parse your data. Please check this, How to convert NSDictionary to custom object.
And yes, I'm using this site to check my json response.
EDIT: Following answer is in javascript!
You can parse your json data with:
var array = JSON.parse(data);
and then you can get everything like this:
var refno = array["value"]["details"][0]["shipment_ref_no"];
you can parse like ...
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *dictValue = [[NSDictionary alloc] initWithDictionary:[jsonDic objectForKey:#"value"]];
NSArray *arrDetails = [[NSArray alloc] initWithArray:[dictValue objectForKey:#"details"]];
for (int i=0; i<arrDetails.count; i++)
{
NSDictionary *dictDetails=[arrDetails objectAtIndex:i];
NSDictionary *dictContact = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"point_of_contact"]];
NSDictionary *dictProduct = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"products"]];
}
NSDictionary *response = //Your json
NSArray *details = response[#"value"][#"details"]
etc. Pretty easy
Update your code as follows. You are trying to read the details array from the top level whereas in your data its inside the value key. So you should read the value dict and within that read the details array.
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"];
NSArray *argsArray = [[NSArray alloc] initWithArray:[valueDict objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
I think your problem is that you have:
NSLog(#"keys = %#", jsonDic[#"values"]);
But it should be:
NSLog(#"keys = %#", jsonDic[#"value"]);
Below is code for parsing JSON array. i have used to parse JSON array from file but you can also do this using response link also.I have provided code for both and are below.
// using file
NSString *str = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
NSData *data = [[NSData alloc]initWithContentsOfFile:str];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
// using url
NSURL *url = [NSURL URLWithString:#"www.xyz.com"]; // your url
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
IOS newb here having trouble with debugging.
Am trying to handle a json feed but code below is breaking at
- (void)viewDidLoad {
[super viewDidLoad];
shnote = #"shnote”;
lnote = #"lnote”;
myObject = [[NSMutableArray alloc] init];
self.title=#"Challenges";
NSData *jsonSource = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://www.~~/webservice.php"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
//BREAKS HERE
NSString *shnote_data = [dataDict objectForKey:#"shnote”];
//ABOVE LINE HIGHLIGHTED IN GREEN AT BREAKPOINT
NSString *lnote_data = [dataDict objectForKey:#"lnote”];
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
shnote_data, shnote,lnote_data, lnote,nil];
[myObject addObject:dictionary];
}
/*
*/
}
The line highlighted in console is
dataDict = (NSDictionary *const)#"notes"
notes is name of table but other than that I am clueless.
Would appreciate any suggestions.
Your data source is of the format:
{
"notes": [
{
"row": {
"shnote": <...>,
"lnote": <...>
}
},
{
"row": {
"shnote": <...>,
"lnote": <...>
}
},
<...>
]
}
Steps to fetch each row content should therefore be:
Read value of notes property
Iterate through each row
Read value of row property
Read shnote and lnote properties
You're missing steps 1, 2 and 3. In code:
NSURL *url = [NSURL URLWithString:#"http://www.~~/webservice.php"];
NSData *jsonSource = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonSource options:NSJSONReadingMutableContainers error:nil];
NSDictionary *notes = jsonObject[#"notes"];
for(NSDictionary *note in notes) {
NSDictionary *row = note[#"row"];
NSString *shnote = row[#"shnote"];
NSString *lnote = row[#"lnote"];
NSLog(#"%#, %#", shnote, lnote);
}
I have an array that loaded with data from other method. The data type is like that in the debug for KEYS as in the code.
<__NSArrayI 0x9e82fc0>(
{
"choice_name" = "Data0";
},
{
"choice_name" = "Data1";
},
{
"choice_name" = "Data2";
},
Then I have called it twice in different method as I commented below and I get the value of the arrray: array0 or array1 nil. Where would be my problem?
- (void)requestPosistion:(ASIFormDataRequest *)request{
NSData *responseData = [request responseData];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *result = [jsonString JSONValue];
[jsonString release];
if (![SettingVO isValidResponce:result]) return;
CXMLDocument *doc = [[[CXMLDocument alloc] initWithXMLString:[result objectForKey:#"Response"] options:0 error:nil] autorelease];
NSArray *nodes = [doc nodesForXPath:#"/root" error:nil];
NSLog(#"choiceList is %#", nodes);
if([[[[nodes objectAtIndex:0] attributeForName:#"success"] stringValue] isEqualToString:#"true"])
{
NSArray *nodes3 = NULL;
nodes3 = [doc nodesForXPath:#"/root/cl_choicelist/cl_choice" error:nil];
NSLog(#"node3%#", nodes3);
res = [[NSMutableArray alloc] init];
for (CXMLElement *node in nodes3) {
item = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [node childCount]; counter++) {
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
}
[item setObject:[[node attributeForName:#"choice_name"] stringValue] forKey:#"choice_name"];
NSLog(#"item %#", item);
[res addObject:item];
[item release];
}
NSLog(#"res %#", res);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects:res forKeys:res];
//NSArray *keys = [plistDict allKeys];
//NSArray *array0 = [[NSArray alloc] initWithArray:[plistDict valueForKey:#"choice_name"]]; //array0 = nil.
NSArray *array1 = [plistDict objectForKey:#"choice_name"]; //array1 = nil.
Working code looks like that:
[[res objectAtIndex:0] objectForKey:#"choice_name"] //returns Data0
[[res objectAtIndex:1] objectForKey:#"choice_name"] //returns Data1
Most probably you want to use "indexPath" at objectAtIndex:
[[res objectAtIndex:[indexPath row]] objectForKey:#"choice_name"]
<__NSArrayI 0x9e82fc0>( { "choice_name" = "Data0"; }, { "choice_name" = "Data1"; }, { "choice_name" = "Data2"; },
This is an array. Inside the array you have object of NSDictionary with key "choice_name".
So in order to retrieve you need to iterate through the array to get all the kvp.
Replace your line with:
NSString *str = [plistDict valueForKey:#"choice_name"];
You have string for that key nor array.
Is always good to make sure your plistDict is not nil.
In NSDictionary you can have onelly one pair with key #choice_name. Even if you "put" more then one in NSDictionary, all other will just override previous value.
so valueForKey can return onelly one object and not the whole array, because there is onelly one key #choice_name.