I am trying to convert a NSMutableDictionary to json on ios.
NSMutableDictionary *offers = [[NSMutableDictionary alloc] init ];
for(int i=0;i<2;i++) {
NSMutableDictionary *myOffer = [[NSMutableDictionary alloc]init];
[myOffer setObject:#"3" forKey:#"id"];
[myOffer setObject:#"34" forKey:#"price"];
[myOffer setObject:#"3" forKey:#"quantity"];
[offers setObject:myOffer forKey:[NSString stringWithFormat:#"%i",i]];
}
NSError *errorOffers;
NSData *jsonDataOffers = [NSJSONSerialization dataWithJSONObject:offers
options:0
error:&errorOffers];
NSString* aStrOffers;
aStrOffers = [[NSString alloc] initWithData:jsonDataOffers encoding:NSUTF8StringEncoding];
I am getting the result.
"offers": {
"0": {
"id": "3",
"quantity": "3",
"price": "34"
},
"1": {
"id": "3",
"quantity": "3",
"price": "34"
}
}
But I need it as
"offers": {
[ {
"id": "3",
"quantity": "3",
"price": "34"
},
{
"id": "3",
"quantity": "3",
"price": "34"
}
]
}
(no indices , but square bracket ) Please advice.
The example below does exactly what you need. You need an array instead of a dictionary. Because a dictionary has keys that need to be defined.
NSMutableArray *offers = [[NSMutableArray alloc] init];
for(int i=0;i<2;i++) {
NSMutableDictionary *myOffer = [[NSMutableDictionary alloc]init];
[myOffer setObject:#"3" forKey:#"id"];
[myOffer setObject:#"34" forKey:#"price"];
[myOffer setObject:#"3" forKey:#"quantity"];
[offers addObject:myOffer];
}
NSError *errorOffers;
NSData *jsonDataOffers = [NSJSONSerialization dataWithJSONObject:offers
options:0
error:&errorOffers];
NSString* aStrOffers;
aStrOffers = [[NSString alloc] initWithData:jsonDataOffers encoding:NSUTF8StringEncoding];
This code is good for you
{"jsonArray":[{"id":"3","quantity":"3","price":"34"},{"id":"3","quantity":"3","price":"34"}]}
NSMutableDictionary *offers = [[NSMutableDictionary alloc] init ];
NSMutableArray *array = [NSMutableArray array];
for(int i=0;i<2;i++) {
NSMutableDictionary *myOffer = [[NSMutableDictionary alloc]init];
[myOffer setObject:#"3" forKey:#"id"];
[myOffer setObject:#"34" forKey:#"price"];
[myOffer setObject:#"3" forKey:#"quantity"];
[array addObject:myOffer];
}
[offers setObject:array forKey:#"jsonArray"];
NSError *errorOffers;
NSData *jsonDataOffers = [NSJSONSerialization dataWithJSONObject:offers
options:0
error:&errorOffers];
NSString* aStrOffers;
aStrOffers = [[NSString alloc] initWithData:jsonDataOffers encoding:NSUTF8StringEncoding];
NSLog(#"%#",aStrOffers);
NSMutableDictionary *offers = [[NSMutableDictionary alloc] init ];
NSMutableArray *offerDetails = [[NSMutableArray alloc] init];
for(int i=0;i<2;i++) {
NSMutableDictionary *myOffer = [[NSMutableDictionary alloc]init];
[myOffer setObject:#"3" forKey:#"id"];
[myOffer setObject:#"34" forKey:#"price"];
[myOffer setObject:#"3" forKey:#"quantity"];
[offerDetails addObject:myOffer];
}
[offers setObject:offerDetails forKey:#"offers"];
NSError *errorOffers;
NSData *jsonDataOffers = [NSJSONSerialization dataWithJSONObject:offers
options:0
error:&errorOffers];
NSString* aStrOffers;
aStrOffers = [[NSString alloc] initWithData:jsonDataOffers encoding:NSUTF8StringEncoding];
NSLog(#"%#", aStrOffers);
You need to set the data to the NSDictionary first and then make that to the NSMutableArray and use the array for the NSJSonSerialization , then you will get the output as you are Expected.
[.... ] --> Indicates the NSArray objects.
{.....} --> Indicates the NSDictionary objects.
Related
I am trying to send a post request to create a record in Google contacts from my app and I am sending the "name" field in the request body as below.
-(void)exportGoogleContact:(NSString*)name {
CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePost;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:#"Accesstoken"];
NSLog(#"token is %#",token);
dataModel.apiUrl = [NSString stringWithFormat:#"https://people.googleapis.com/v1/people:createContact?access_token=%#",token];
NSString * requestString = [NSString stringWithFormat:#"name=%#",name];
dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self callBackSelector:#selector(exportGoogleReponseData:)
dataModel:dataModel];
[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
}
I am getting the following error message:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"name\":
Cannot bind query parameter. Field 'name' could not be found in
request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"name\": Cannot bind query parameter. Field 'name' could not be found in request message."
}
]
}
]
}
}
Anyone have idea, how to fix the this error, Thanks in advance
Here is the full code which is working fine for me
// Export to Google contacts
-(void)exportGoogleContact:(NSString*)name mobile:(NSString *)mobile phone:
(NSString *)phone email:(NSString*)email company:(NSString *)company
designation:
(NSString *)designation website:(NSString *)website address:(NSString
*)address
notes:(NSString*)notes {
CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePostJson;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:#"Accesstoken"];
NSLog(#"token is %#",token);
NSMutableDictionary * reqDict = [[NSMutableDictionary alloc] init];
[reqDict setObject:name forKey:#"Name"];
[reqDict setObject:mobile forKey:#"MobileValue"];
[reqDict setObject:phone forKey:#"PhoneValue"];
[reqDict setObject:email forKey:#"EmailValue"];
[reqDict setObject:company forKey:#"CompanyValue"];
[reqDict setObject:designation forKey:#"DesignasionValue"];
[reqDict setObject:website forKey:#"WebsiteValue"];
[reqDict setObject:address forKey:#"AddressValue"];
if([notes isEqual: #""]){
notes = #"Added through APPName";
}
[reqDict setObject:notes forKey:#"NotesValue"];
dataModel.apiUrl = [NSString
stringWithFormat:#"https://people.googleapis.com/v1/people:createContact?
access_token=%#",token];
//NSString * requestString = [NSString stringWithFormat:#"name=%#",name];
NSString *requestString = [CLUtils createJsonContentForGoogleSync:reqDict];
dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self
callBackSelector:#selector(exportGoogleReponseData:)
dataModel:dataModel];
[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
}
//Here is the code to create json request
+ (NSString *) createJsonContentForGoogleSync:(NSDictionary *)reqDict{
NSMutableDictionary *phoneDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict3 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict4= [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict5 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict6 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *companyDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *emailDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *designatioDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *websiteDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *nameDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mobileDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *addressDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *notesDataDict = [[NSMutableDictionary alloc] init];
[nameDataDict setObject:[reqDict objectForKey:#"Name"] forKey:#"givenName"];
[websiteDataDict setObject:[reqDict objectForKey:#"WebsiteValue"]
forKey:#"value"];
//[designatioDataDict setObject:[reqDict objectForKey:#"DesignasionValue"]
forKey:#"value"];
[emailDataDict setObject:[reqDict objectForKey:#"EmailValue"] forKey:#"value"];
[designatioDataDict setObject:[reqDict objectForKey:#"DesignasionValue"]
forKey:#"title"];
[companyDataDict setObject:[reqDict objectForKey:#"CompanyValue"]
forKey:#"name"];
[mobileDataDict setObject:[reqDict objectForKey:#"MobileValue"]
forKey:#"value"];
[mobileDataDict setObject:#"mobile" forKey:#"type"];
[phoneDataDict setObject:[reqDict objectForKey:#"PhoneValue"] forKey:#"value"];
[phoneDataDict setObject:#"work" forKey:#"type"];
NSArray *companyArry;
if(![[companyDataDict objectForKey:#"name"] isEqual: #""]){
companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];
}
else{
[companyDataDict setObject:#" " forKey:#"name"];
companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];
}
NSArray *phoneNosArry;
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,nil];
if([reqDict.allKeys containsObject:#"PhoneValue2"]){
[phoneDataDict2 setObject:[reqDict objectForKey:#"PhoneValue2"]
forKey:#"value"];
[phoneDataDict2 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2 ,nil];
}
if([reqDict.allKeys containsObject:#"PhoneValue3"]){
[phoneDataDict3 setObject:[reqDict objectForKey:#"PhoneValue3"]
forKey:#"value"];
[phoneDataDict3 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3
,nil];
}
if([reqDict.allKeys containsObject:#"PhoneValue4"]){
[phoneDataDict4 setObject:[reqDict objectForKey:#"PhoneValue4"]
forKey:#"value"];
[phoneDataDict4 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray
}
if([reqDict.allKeys containsObject:#"PhoneValue5"]){
[phoneDataDict5 setObject:[reqDict objectForKey:#"PhoneValue5"]
forKey:#"value"];
[phoneDataDict5 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5 ,nil];
}
if([reqDict.allKeys containsObject:#"PhoneValue6"]){
[phoneDataDict6 setObject:[reqDict objectForKey:#"PhoneValue6"] forKey:#"value"];
[phoneDataDict6 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5,phoneDataDict6 ,nil];
}
//[phoneDataDict addEntriesFromDictionary:mobileDataDict];
[addressDataDict setObject:[reqDict objectForKey:#"AddressValue"] forKey:#"formattedValue"];
[notesDataDict setObject:[reqDict objectForKey:#"NotesValue"] forKey:#"value"];
[notesDataDict setObject:#"TEXT_PLAIN" forKey:#"contentType"];
NSMutableDictionary *parentDict = [[NSMutableDictionary alloc] init];
[parentDict setObject:nameDataDict forKey:#"names"];
[parentDict setObject:emailDataDict forKey:#"emailAddresses"];
[parentDict setObject:companyArry forKey:#"organizations"];
[parentDict setObject:websiteDataDict forKey:#"urls"];
// [parentDict setObject:designatioDataDict forKey:#"occupations"];
//[parentDict setObject:phoneDataDict forKey:#"phoneNumbers"];
[parentDict setObject:phoneNosArry forKey:#"phoneNumbers"];
//[parentDict setObject:mobileDataDict forKey:#"phoneNumbers"];
[parentDict setObject:addressDataDict forKey:#"addresses"];
[parentDict setObject:notesDataDict forKey:#"biographies"];
NSData *resultData = [NSJSONSerialization dataWithJSONObject:parentDict
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString ;
if(resultData != nil){
jsonString = [[NSString alloc] initWithData:resultData
encoding:NSUTF8StringEncoding];
}
NSLog(#"####### Final json string is %#",jsonString);
return jsonString;
}
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];
}
how i can create Dictionary that when i create jsondata with it, json looks like :
"historyStep":[
{
"counter": "50",
"timestamp": "1461674383632"
}
]
I did this :
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:jsonDictOth,#"historyStep", nil];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:NSJSONWritingPrettyPrinted
error:&error];
but it looks :
historyStep = {
counter = 810;
timestamp = "1464957395241.447998";
};
You are missing a level: NSDictionary (top level) with NSArray of NSDictionary in the top level key historyStep:
NSMutableDictionary *topLevel = [[NSMutableDictionary alloc] init];
NSArray *historySteps = [[NSMutableArray alloc] init];
//Here you may have a for loop in case there are more steps
NSDictionary *aStep = #{#"counter":#"50", #"timestamp":#"1461674383632"};
[historySteps addObject:aStep]
[topLevel setObject:historySteps forKey#"historyStep"];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:topLevel
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *innerDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:#"50", #"counter",#"1461674383632", #"timestamp", nil];
NSArray *array = [[NSArray alloc]initWithObjects:innerDictionary, nil];
NSDictionary *outerDict = [[NSDictionary alloc]initWithObjectsAndKeys:array, #"historyStep", nil];
Use this code it will work perfectly.
Your code should be like,
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject:jsonDictOth];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:arr,#"historyStep", nil];
NSLog(#"jsonMain is %#",jsonDictMain);
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:0
error:&error];
It's output is,
jsonMain is {
historyStep = (
{
counter = 810;
timestamp = "1464957395241.447998";
}
);
}
You just missed one array between
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);