I have JSON format requirement something like this.
{
"first_name" : "XYZ",
"last_name" : "ABC"
}
I have values in NSString.
NSString strFName = #"XYZ";
NSString strLName = #"ABC";
NSString strKeyFN = #"first_name";
NSString strKeyLN = #"last_name";
And I use NSMutableDictionary
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
then output is
{
first_name = XYZ,
last_name = ABC
}
So I don't want "=" separating key & values instead I want ":" to separate key and values
I have went most of the stack overflow questions but didn't help getting "=" only in output
So please any help ?
Here is your answer :
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSInteger number = 15;
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSString *numValue = #"Number";
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:strFName forKey:strKeyFN];
[dic setObject:strLName forKey:strKeyLN];
[dic setObject:[NSNumber numberWithInt:number] forKey:numValue];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dic] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON %#",jsonString);
You write this code after your NSDictionary
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSDictionary *ictionary = [NSDictionary dictionaryWithObjectsAndKeys:
strKeyFN, strFName,strKeyLN, strLName,nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"dictionary as string:%#", jsonString);
NSString *strFName = #"ABC";
NSString *strLName = #"XYZ";
NSString *strKeyFN = #"last_name";
NSString *strKeyLN = #"first_name";
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dict] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStrng = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Your required JSON is %#",jsonStrng);
try this:-
NSString *cleanedString1 =[strFName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSString *cleanedString2 =[strLName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:
cleanedString1, strKeyFN,
cleanedString2, strKeyLN,nil];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
this very robust code to achieve you goal
NSDictionary *userDic = #{strKeyFN:strFName,strKeyLN:strLName};
you have to convert NSMutableDictionary into NSData
then convert the NSData Into json string you want
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jasonString= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
Related
Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}
try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}
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 trying to learn JSON with IOS since I'm a beginner in IOS devices, i tried this code so far
-(void)retriveData
{
NSURL *url = [NSURL URLWithString:#"http://localhost/testjson.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
cities = [[NSMutableArray alloc] init];
for (int i=0; i<json.count; i++) {
NSString *cID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[json objectAtIndex:i] objectForKey:#"CityName"];
NSString *cState = [[json objectAtIndex:i] objectForKey:#"CityState"];
NSString *cPopulation = [[json objectAtIndex:i] objectForKey:#"CityPopulation"];
NSString *cCountry = [[json objectAtIndex:i] objectForKey:#"Country"];
Country *myCity = [[Country alloc] initWithCityID:cID andCityName:cName andCityState:cState andCityPopulation:cPopulation andCityCountry:cCountry];
[cities addObject:myCity];
}
}
Anyone can show me now how i can print the data? this is the json file
[{"0":"1","id":"1","1":"Muscat","CityName":"Muscat","2":"Muscat","CityState":"Muscat","3":"25000","CityPopulation":"25000","4":"Oman","Country":"Oman"},{"0":"2","id":"2","1":"Bawsher","CityName":"Bawsher","2":"Muscat","CityState":"Muscat","3":"10000","CityPopulation":"10000","4":"Oman","Country":"Oman"},{"0":"3","id":"3","1":"AlMawalih","CityName":"AlMawalih","2":"Seeb","CityState":"Seeb","3":"5000","CityPopulation":"5000","4":"Oman","Country":"Oman"},{"0":"4","id":"4","1":"Oran","CityName":"Oran","2":"Oran","CityState":"Oran","3":"100000","CityPopulation":"100000","4":"Algeria","Country":"Algeria"},{"0":"5","id":"5","1":"Constantine","CityName":"Constantine","2":"Constantine","CityState":"Constantine","3":"150000","CityPopulation":"150000","4":"Algeria","Country":"Algeria"}]
Below is my very understandable and basic coding according to your question.It is helpful for you.
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost/testjson.php"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in GOOGLE.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSLog(#"The json output array is - %#",jsonArray);
for(int i=0;i>[jsonArray count];i++)
{
NSString *strZero = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"0"]];
NSLog(#"The zero is-%#",strZero);
NSString *strOne = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"1"]];
NSLog(#"The One is-%#",strOne);
NSString *strTwo = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"2"]];
NSLog(#"The Two is-%#",strTwo);
NSString *strThree = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"3"]];
NSLog(#"The three is-%#",strThree);
NSString *strFour = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"4"]];
NSLog(#"The four is-%#",strFour);
NSString *strID = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"id"]];
NSLog(#"The ID is-%#",strID);
NSString *strCityName = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityName"]];
NSLog(#"The CityName is-%#",strCityName);
NSString *strCityState = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityState"]];
NSLog(#"The CityState is-%#",strCityState);
NSString *strCityPopulation = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityPopulation"]];
NSLog(#"The CityPopulation is-%#",strCityPopulation);
NSString *strCountry = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"Country"]];
NSLog(#"The Country is-%#",strCountry);
}
By printing you mean show the data in the console ?
Did you try this ?
NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data: %#", str);
I have an Array of Roll Numbers
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
I need to send this array in a Web Service request
whose format is like this (in JSON format)
JSON data
{
"existingRoll":["22","34","45","56"], // Array of roll numbers
"deletedRoll":["20","34","44","56"] // Array of roll numbers
}
but I am facing problem in converting Array of Roll numbers (rollArray) into json String
in the desired format.
I am trying this
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:[rollArray componentsJoinedByString:#","] forKey:#"existingRoll"];
NSString *str = [Self convertToJSONString:postDict]; // converts to json string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:0 error:nil];
[request setHTTPBody:jsonData];
I am using iOS 7
There is no need to use the following code snippets:
[rollArray componentsJoinedByString:#","]
NSString *str = [Self convertToJSONString:postDict];
You can create JSON by using the following code:
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:rollArray forKey:#"existingRoll"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSLog(#"%#",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
Try this :
NSDictionary *object = #{
#"existingRoll":#[#"22",#"34",#"45",#"56"],
#"deletedRoll":#[#"20",#"34",#"44",#"56"]
};
if ([NSJSONSerialization isValidJSONObject:object]) {
NSData* data = [ NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil ];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(str);
}
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:#"Login" forKey:#"methodName"];
[postDict setValue:#"admin" forKey:#"username"];
[postDict setValue:#"12345" forKey:#"password"];
[postDict setValue:#"mobile" forKey:#"clientType"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:#"jsonRequest=%#", urlString];
//#"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345\",\"clientType\":\"web\"}";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
You can use following method to get Json string from any type of NSArray :
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:rollArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Json string is: %#", jsonString);
I get the data from an XML file and I am storing it in NSData object. I want to convert that NSData into an NSDictionary and store that data in a plist.
My code is as follows:
NSURL *url = [NSURL URLWithString:#"http://www.fubar.com/sample.xml"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"%#", data);
To convert the data, I am using:
- (NSDictionary *)downloadPlist:(NSString *)url {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
if (!err) {
NSString *errorDescription = nil;
NSPropertyListFormat format;
NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];
if (!errorDescription)
return samplePlist;
[errorDescription release];
}
return nil;
}
Can anyone please tell me how to do that?
or this:
NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *jsonParser = [SBJSON new];
NSDictionary* result = (NSDictionary*)[jsonParser objectWithString:dataStr error:nil];
[jsonParser release];
[dataStr release];
Try this code:
NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];
NSArray *keys = [NSArray arrayWithObjects:#"key1", #"key2", #"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
for (id key in dictionary) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"Login" ofType:#"plist"];
[dictionary writeToFile:path atomically:YES];
//here Login is the plist name.
Happy coding