How can i create a json array in below format:
[{"id":"8"},{"id":"9"}]
Using Nsmutable dictionary we can create an above format,but key should be different.
NSDictionary *dict1 = #{
#"id" : #"8"
};
NSDictionary *dict2 = #{
#"id" : #"9"
};
NSArray *array = #[dict1,dict2];
NSData *jsonData=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Output
[
{
"id" : "8"
},
{
"id" : "9"
}
]
Related
[
{
"c_name" : "r",
"email_id" : "r",
"phn_no" : "2",
"c_id" : "1"
},
{
"c_name" : "e",
"email_id" : "e",
"phn_no" : "4",
"c_id" : "2"
}
]
This the output I received as JSON string. Now how can I access these data? I used NSJSONSerialization class:
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr_mcontacts options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Output: %#",jsonString);
I think you have an array of dictionaries. Something like this should work:
NSError *writeError;
NSError *error;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *arrayOfDictionary = [[NSMutableArray alloc] init];
arrayOfDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictionary = [myArray objectAtIndex:0];
NSString *valueString= [dictionary objectForKey: #"c_name"];
For accessing data you use a dictionary instead of string. The code below shows
NSDictionary *responseDict=[NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingMutableContainers error:&error]; for(NSArray *a in responseDict)
{[cnamearray addobject [a valueforKey:#"c_name"]];
}NSLog(#"The cnamearray contains:", cnamearray);
The output will be The cnamearray contains: { r,e}
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);
I'm in need take the data that passes facebook me with the scores of the players, but I can not return the values that are within the braces in xcode.
Example:
{
"data": [
{
"user": {
"id": "927806543903674",
"name": "Renata Gabi"
},
"score": 333,
"application": {
"name": "Player 2",
"namespace": "quemsoueubiblico",
"id": "303489829840143"
}
},
{
"user": {
"id": "964974026864922",
"name": "Player 1"
},
"score": 230,
"application": {
"name": "My Game",
"namespace": "quemsoueubiblico",
"id": "303489829840143"
}
}
]
}
In android I use this
...
jgame = jObject.getJSONArray("data");
...
score = jgame.getString("score");
name = jgame.getJSONObject("user").getString("name");
photo_id = jgame.getJSONObject("user").getString("id");
for ios in xcode, I was trying this, but is not working
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.escoladepsicanalisekoinonia.com/teste/index.html"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *score_data = [dataDict objectForKey:#"score"];
NSString *name_data = [dataDict objectForKey:#"name"];
NSString *id_data = [dataDict objectForKey:#"id"];
NSLog(#.........);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
score_data, score,
name_data, name,
id_data, id,
nil];
[myObject addObject:dictionary];
}
I am not able to adjust the "data" facebook graph, and get the subclasses
The data item in your JSON sample is an array, but you're not taking this into account in your code. Try this:
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.escoladepsicanalisekoinonia.com/teste/index.html"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
NSArray *data = [jsonObjects objectForKey:#"data"];
for (NSDictionary *dataDict in data) {
NSString *score_data = [dataDict objectForKey:#"score"];
NSDictionary *user_data = [dataDict objectForKey:#"user"];
NSString *name_data = [user_data objectForKey:#"name"];
NSString *id_data = [user_data objectForKey:#"id"];
NSLog(#.........);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
score_data, score,
name_data, name,
id_data, id,
nil];
[myObject addObject:dictionary];
}
This question already has an answer here:
Parsing Json to get all the contents in one NSArray
(1 answer)
Closed 8 years ago.
for the moment I fill in my array directly by a native objective-C code :
Datas *pan1 = [[Datas alloc] initWithTitle:#"My array 1" title:#"Shakespeare's Book" location:#"London"];
Datas *pan2 = [[Datas alloc] initWithTitle:#"My array 2" title:#"Moliere's Book" location:#"London"];
NSMutableArray *datasListe = [NSMutableArray arrayWithObjects:pan1, pan2, nil];
But I want to fill this NSMutableArray by this Json list :
{
"myIndex" : [
{
"name":"My array 1",
"title": "Shakespeare's Book",
"location": "London"
},
{
"name":"My Array 2",
"title": "Moliere's Book",
"location": "Paris"
}
]
}
Anyone have ideas? Thanks much!
This json data can be parse very easily like this.
NSError *e;
NSArray *dic= [NSJSONSerialization JSONObjectWithData: jsondata options: NSJSONReadingMutableContainers error: &e];
NSMutableArray *datasListe = [[NSMutableArray alloc] init];
NSMutableArray *data = [dic objectForKey:#"myIndex"];
//Now you have array of dictionaries
for(NSDictionary *dataDic in data){
NSString *name = [dataDic objectForkey:#"name"];
NSString *title = [dataDic objectForKey#"title"];
NSString *location = [dataDic objectForKey#"location"];
Datas *pan= [[Datas alloc] initWithTitle:name title:title location:location];
[dataList addObject:pan];
}
NSDictionary *firstDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"Raja", #"name",
#"Developer", #"title",
#"USA", #"location",
nil];
NSDictionary *secondDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"Deepika", #"name",
#"Engieer", #"title",
#"USA", #"location",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:firstDictionary];
[arr addObject:secondDictionary];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonArray as string:\n%#", jsonString);
i'm stuck with a problem!
I have a String with JSON like:
{"UserName":"username","PassWord":"password"}
I build this JSON string with xcode like:
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
[jsonDict setValue:self.usernameField.text forKey:#"UserName"];
[jsonDict setValue:self.passwordField.text forKey:#"PassWord"];
NSLog(#"Dict: %#",jsonDict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON String: %#",jsonString);
NSString *postStr = [NSString stringWithFormat:#"%#",jsonString];
But now i want a string with JSON like:
{ "comp": [
{ "id": "1" },
{ "id": "2" },
{ "id": "3" }
],
"contact": [
{ "mail": "some#email.com", "name": "Name" },
{ "mail": "email#email.com", "name": "Name" }
]
}
But how can i do this? Can somebody help me out?
This will give you comp. Using what you have and this example, you should be able to get contact easily.
NSDictionary *id1 = [NSDictionary dictionaryWithObjectsAndKeys:
#"1", "id", nil];
NSDictionary *id2 = [NSDictionary dictionaryWithObjectsAndKeys:
#"2", "id", nil];
NSDictionary *id3 = [NSDictionary dictionaryWithObjectsAndKeys:
#"3", "id", nil];
NSArray *ids = [NSArray arrayWithObjects:id1, id2, id3, nil];
NSDictionary *comp = [NSDictionary dictionaryWithObjectsAndKeys:ids, #"comp", nil];
Also, check out the following library for easy serialization/deserialization.
JSONKit