Get NSString as NSArray from NSDictionary - ios

I've the following data in NSDictionary for an object field_names that has below value.
{dBur0z9,nr8r0,R0ru,jrurw,qB5rz9ry},{gr2,Z5uzr,Rwxyr5z0Ar5},^~gr2~cry69v~br9rtyz~Z03r4rsru^~Z5uzr~Uvy3z~dB4srz^5B33,(),9ruI,evD3rsv3,,HLK,evDsBAA65,evDtyvt2s6E,5B33,5B33,5B33,5B33,{6ww},SRiTfUV,5B33,5B33,5B33,5B33
I'm trying to get it as NSArray. I tried
`NSArray *array = [dictionary objectForKey:#"field_name"];
But that returns an NSString not an NSArray. Then I tried to replace { } with [ ] and appended [ ] to make it json array,
NSString *s =[[dictionary objectForKey:#"field_names"] stringByReplacingOccurrencesOfString:#"{" withString:#"["];
s = [s stringByReplacingOccurrencesOfString:#"}" withString:#"]"];
s= [NSString stringWithFormat:#"[%#]",s];
NSDictionary *temp = #{#"array":s };
NSLog(#"%#", [temp objectForKey:#"array"]);
But still I'm getting it as NSString
[[dBur0z9,nr8r0,R0ru,jrurw,qB5rz9ry],[gr2,Z5uzr,Rwxyr5z0Ar5],^~gr2~cry69v~br9rtyz~Z03r4rsru^~Z5uzr~Uvy3z~dB4srz^5B33,(),9ruI,evD3rsv3,,HLK,evDsBAA65,evDtyvt2s6E,5B33,5B33,5B33,5B33,[6ww],SRiTfUV,5B33,5B33,5B33,5B33]
Please help me getting it NSArray!

You're getting it as a string because it is in fact string. I feel like you're trying to parse it as a JSON string??
If so, you first need to have that string in a valid JSON format. Here's an example JSON
{
   "AnArray": [
"string 1",
      "string 2",
      "string 3"
   ]
}
(without the line breaks of course I just added them for readability)
Once you have it as a valid JSON formatted string, you can do this
NSError *error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: [dictionary[#"field_names"] dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &error];
NSArray* YourArray = json[#"AnArray"];

I didn't find any cocoa method for this task, so I replaced , with & that occurs within {} and then used [string componentsSeparatedByString:#","] method to get it as NSArray. Below is the code
-(NSString *)prepareFields:(NSString *)string {
NSString *remainingString =string;
NSString *newString = #"";
#try {
while ([remainingString rangeOfString:#"{"].location != NSNotFound ) {
NSUInteger from = [remainingString rangeOfString:#"{"].location ,
to =[remainingString rangeOfString:#"}"].location+1 ;
NSString *part = [[remainingString substringWithRange:NSMakeRange(from,to)] stringByReplacingOccurrencesOfString:#"," withString:#"&"];
remainingString = [remainingString substringFromIndex:to];
if([newString isEqualToString:#""])
newString = [part substringWithRange:NSMakeRange([part rangeOfString:#"{"].location,[part rangeOfString:#"}"].location+1)];
newString = [NSString stringWithFormat:#"%#,%#",newString,[part substringWithRange:NSMakeRange([part rangeOfString:#"{"].location,[part rangeOfString:#"}"].location+1)]];
}
}
#catch (NSException *exception) {
NSLog(#"break %#" ,[exception reason]);
}
if([newString isEqualToString:#""])
newString = remainingString;
else
newString = [NSString stringWithFormat:#"%#,%#",newString,remainingString];
return newString;
}
And then called it
NSLog([[dictionary objectForKey:#"form"] componentsSeparatedByString:#","]);
That gave following array
(
"{dBur0z9&nr8r0&R0ru&jrurw&qB5rz9ry}",
"{dBur0z9&nr8r0&R0ru&jrurw&qB5rz9ry}",
"{gr2&Z5uzr&Rwxyr5z0Ar5}",
"",
"^~gr2~cry69v~br9rtyz~Z03r4rsru^~Z5uzr~Uvy3z~dB4srz^5B33",
"()",
9ruI,
evD3rsv3,
"",
HLK,
evDsBAA65,
evDtyvt2s6E,
5B33,
5B33,
5B33,
5B33,
"{6ww}",
SRiTfUV,
5B33,
5B33,
5B33,
5B33 )

Related

JSON creation in objective c, invalid JSON

I am creating a JSON to be sent in service on checking online its showing error:
Error: Parse error on line 1:
[{\ "SAHExpertCode\"
--^ Expecting 'STRING', '}', got 'undefined'
My JSON is [{\"SAHExpertCode\" : \"\", \"ShiftType\" : \"AM\", \"LocFunId\" : \"CLT0004218\", \"SAHQualCode\" : \"CA\" }]
Please tell me what's wrong and how to correct it.First i am making JSON filterString = [{ "SAHExpertCode" : "", "ShiftType" : "AM", "LocFunId" : "CLT0004218","SAHQualCode" : "CA" }] on checking found it is correct then creating a dictionary NSDictionary*dictData=#{#"MbrId":[USER_DEFAULTS valueForKey:#"MemberId"],#"StrFilter":[NSString stringWithFormat:#"%#",filterString],#"shiftCrtlNos":shftCntrlNmbrs}; NSMutableArray *finalArray = [[NSMutableArray alloc]init]; [finalArray addObject:dictData]; NSString *finalString =[self ConvertArrayToJsonData:finalArray];finalString = [finalString stringByReplacingOccurrencesOfString:#"\n" withString:#""]; finalString = [finalString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];after creation of final string it is generating symbol \ for JSON Conversion my code is -(NSString *)ConvertArrayToJsonData:(NSMutableArray *)array{ NSError error;
NSData jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; NSString *JSONString; if (!jsonData) { NSLog(#"error :%#",error); } else {JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; // NSLog(#"jsonstring:%#",JSONString);
}
return JSONString;
}
//i need JSON like [ { "StrFilter" : "[ { \"SAHExpertCode\" : \"\", \"ShiftType\" : \"PM\", \"LocFunId\" : \"CLT0004218\", \"SAHQualCode\" : \"CA\" }]", "MbrId" : "MBR0000035", "shiftCrtlNos" : "0080013526,0080014697" }] also tell me how to remove \ from String
i replaced the unwanted \ symbols by doing
finalString = [finalString stringByReplacingOccurrencesOfString:#"\" withString:#""]; in the JSON string.
I suggest you go to www.json.org and look at the correct formatting of JSON data. And the easiest way to get correctly formatted JSON is to create an array or dictionary that you want to convert to JSON, and use NSJSONSerialization to do the job.
Just use default NSJSONSerialization method of iOS
in below example i have a "postMenuArray" which I'm converting in JSON.
NSData * postMenuSerial = [NSJSONSerialization dataWithJSONObject:postMenuArray options:0 error:nil];
NSString *Menujson = [[NSString alloc] initWithBytes:[postMenuSerial bytes] length:[postMenuSerial length] encoding:NSUTF8StringEncoding];
Here I got JSON response
Menujson = [Menujson stringByReplacingOccurrencesOfString:#" "withString:#""];
Lastly I remove all the spacing .
Still facing issue try this
Menujson = [Menujson stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString JSON - filtering through data

I am converting JSON data in to NSString using below code:
NSString *json_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data AS STRING %#", json_string);
it returns NSString in this format:
Data AS STRING
{
"success": true,
"terms": "https://currencylayer.com/terms",
"privacy": "https://currencylayer.com/privacy",
"timestamp": 1446673809,
"source": "USD",
"quotes": {
"USDAED": 3.672993,
"USDAFN": 64.980003,
"USDALL": 127.164497,
"USDAMD": 474.480011,
"USDANG": 1.790326,
"USDAOA": 135.225006,
"USDARS": 9.536025,
"USDAUD": 1.398308,
"USDAWG": 1.79,
"USDAZN": 1.04625,
"USDBAM": 1.800851,
"USDBBD": 2,
"USDBDT": 78.666946,
"USDBGN": 1.80115,
"USDBHD": 0.37727,
"USDBIF": 1562.5,
"USDBMD": 1.00005,
"USDBND": 1.403198,
"USDBOB": 6.899293,
"USDBRL": 3.80025,
"USDBSD": 0.999335,
"USDBTC": 0.002372,
"USDBTN": 65.495003,
"USDBWP": 10.55195,
"USDBYR": 17415,
"USDBZD": 1.994983,
"USDCAD": 1.315225,
"USDCDF": 929.999946,
"USDCHF": 0.99331,
"USDCLF": 0.024598,
"USDCLP": 692.094971,
"USDCNY": 6.33525,
"USDCOP": 2837.080078,
"USDCRC": 534.015015,
"USDCUC": 0.99991,
"USDCUP": 0.99978,
"USDCVE": 101.349503,
"USDCZK": 24.907012,
"USDDJF": 177.595001,
"USDDKK": 6.8657,
"USDDOP": 45.400002,
"USDDZD": 107.014999,
"USDEEK": 14.325002,
"USDEGP": 8.029699,
"USDERN": 15.279969,
"USDETB": 21.022499,
"USDEUR": 0.920471,
"USDFJD": 2.157498,
"USDFKP": 0.648499,
"USDGBP": 0.650132,
"USDGEL": 2.395014,
"USDZWL": 322.355011
}
}
I need to get value of "USDGBP" from that string. How can I do that? Preferably stored as double.
Rather than converting it into NSString try converting it in NSDictionary using
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
then you can retrieve value of USDGBP like
double usdgbp = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
double usdgbpValue = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
you can find the value in the string simply extracting a string between 2 string.
NSString *jsonStr = #"long json string";
NSRange str1 = [jsonStr rangeOfString:#"\"USDGBP\":"];
NSRange str2 = [jsonStr rangeOfString:#","];
NSRange strSub = NSMakeRange(str1.location + str1.length, str2.location - str1.location - str1.length);
NSString *valueForUSDGBP = [jsonStr substringWithRange:strSub];
You should use NSJSONSerialization
NSData *jsonData = your data ... ;
NSError *theError = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&theError];
if (theError) {
NSLog(#"%#", theError);
}
else {
double theValue = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
}
If you'd like to have much fun, use NSScanner to parse the string ;)

Incorrectly parse json into NSDictionary

I am trying store text fields data into a NSDictionary from json. I have used SBJson for this.
{
"fields":[
{
"textFields":[
{
"text":"Congratulations",
"textSize":"12"
},
{
"text":"Best Wishes",
"textSize":"15"
},
{
"text":"Test text",
"textSize":"10"
}
]
},
{
"imageFields":[
{
"image":"test1.jpg",
"width":"200",
"height":"100"
},
{
"image":"test2.jpg",
"width":"200",
"height":"100"
}
]
}
]
}
My code:
-(void)readJson{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
But its output as follows.
Dictionary (
(
{
text = Congratulations;
textSize = 12;
},
{
text = "Best Wishes";
textSize = 15;
},
{
text = "Test text";
textSize = 10;
}
),
"<null>"
)
It seems like there are two items in dictionary and one is null. I wanted to put three textfield items into the array. How can i solve this.
Don't use SBJSON. Use NSJSONSerialization.
Don't use valueForKey:, use objectForKey:.
You are mixing up dictionaries and arrays. Don't do that. Use NSArray for arrays.
I am revising your code for better understanding
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
More appropriate way is
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fieldsArr =[jsonDict objectForKey:#"fields"];
for(int i=0;i<[fieldArr count];i++)
{
NSArray *textFieldArr = [fieldArr objectAtIndex: i];
for(int j=0;j<[textFieldArr count];j++)
{
NSDictionary *dicTextField = [textFieldArr objectAtIndex: j];
NSString *text = [dicTextField objectForKey: #"text"];
NSString *textSize = [dicTextField objectForKey: #"textSize"];
}
}
}
For quick help
treat { as dictionary and [ as array.
Hope, i am helpful to you.
As your json format, [jsonDict valueForKey:#"fields"] will return an array not dictionary so your code must be
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fields = [jsonDict objectForKey:#"fields"];
NSDictionary *fieldsDict = fields[0];
NSArray *textFieldsDict = [fieldsDict objectForKey:#"textFields"];
I have corrected the json format and used NSJSONSerialization,
{"fields":
{"textFields":
[ {"text":"Congratulations", "textSize":"12"},
{"text":"Best Wishes", "textSize":"15"},
{"text":"Test text", "textSize":"10"}
],
"imageFields":
[ {"image":"test1.jpg","width":"200", "height":"100"},
{"image":"test2.jpg", "width":"200", "height":"100"}
]
}
}
-(void)readJson
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSDictionary *fields = [jsonDict objectForKey:#"fields"];
NSArray *textArray=[fields objectForKey:#"textFields"] ;
NSLog(#"--- %#",textArray );
}

iOS: JSON displays dictionary out of order. How to present a reordering?

Say we have the following dictionary:
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:currentItem], #"item number",
[NSNumber numberWithInt:([[item valueForKey:#"section"] intValue]+1)], #"section number",
currentDate, #"date of item",
[NSNumber numberWithDouble:timeDifference], #"time difference in millis",
nil];
Then I get the following output:
{
"time difference in millis" : 5.220093071460724,
"section number" : 1,
"date of item" : "28/04/2014 15:56:54,234",
"item number" : 3
}
I use the following code to convert the dictionary to JSON:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\\" withString:#""];
How can I manipulate the order in which the JSON string shows its keys. For example, I would like to have:
{
"item number" : 3,
"section number" : 1,
"date of item" : "28/04/2014 15:56:54,234",
"time difference in millis" : 5.220093071460724
}
or something else. The point is that I want control over this process. How do I get it? My first thought was writing a parser that shows the ordering in the way that I want.
Here are similar questions, but my emphasis is on manipulating the order instead of just recreating the order in which I put it from the dictionary.
JSON format: getting output in the correct order
Need JSON document that is generated to be in same order as objects inserted in NSMutableDictionary in iOS
NSDictionary is not ordered by definition.
Easiest will be to wrap everything into NSArray if you want to have same order.
To restate the question: how to take an inherently unordered input, produce a string who's specification is inherently unordered, but control the ordering of that string.
Reformatting the dictionary as an array would let you control input ordering, but produce a different output format.
The only reason I can imagine wanting to do this is if wish to use the JSON string not as JSON, but just as a string. The question can then be restated as just lexically reformatting the string.
How general purpose must it be? Can we assume that the JSON has simple, scalar values? Then...
- (NSString *)reorderJSON:(NSString *)json keys:(NSArray *)orderedKeys {
NSArray *splitJson = [json componentsSeparatedByString:#","];
NSMutableArray *splitResult = [NSMutableArray array];
for (NSString *key in orderedKeys) {
for (NSString *splitPair in splitJson) {
if ([self jsonPair:splitPair hasKey:key]) {
NSString *trimmedSplitPair = [splitPair stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"{}"]];
[splitResult addObject:trimmedSplitPair];
}
}
}
NSString *joinedResult = [splitResult componentsJoinedByString:#","];
return [NSString stringWithFormat:#"{%#\n}", joinedResult];
}
- (BOOL)jsonPair:(NSString *)pair hasKey:(NSString *)key {
// pair should begin with double quote delimited key
NSString *trimmedPair = [pair stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *splitPair = [trimmedPair componentsSeparatedByString:#"\""];
return [splitPair[1] isEqualToString:key];
}
Call it like this:
- (void)testJson {
NSDictionary *d = #{ #"time difference in millis": #5.220093071460724,
#"section number": #1,
#"date of item" : #"28/04/2014 15:56:54,234",
#"item number": #3};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSArray *orderedKeys = #[ #"item number", #"section number", #"date of item", #"time difference in millis"];
NSString *result = [self reorderJSON:jsonString keys:orderedKeys];
NSLog(#"%#", result);
}
You shouldn't want that. Dictionaries have no order and writing some code that uses the order will just lead to problems in the future.
That said, if you want to, you can write your own code to generate the JSON string from your (ordered) array of keys and dictionary of values.

Store App names in NSArray from JSON DATA which Stored in NSDictionary

I have retrive following response form Server in JSON format which I have sucessfully store in NSDictionary.
{
"#companyName" = "MobileAPPSDeveloper";
"#generatedDate" = "8/6/13 2:41 AM";
"#version" = "1.0";
application = (
{
"#apiKey" = 234FXPQB36GHFF2334H;
"#createdDate" = "2013-03-01";
"#name" = FirstApp;
"#platform" = iPhone;
},
{
"#apiKey" = 3PF9WDY234546234M3Z;
"#createdDate" = "2013-02-01";
"#name" = SecondAPP;
"#platform" = iPhone;
},
{
"#apiKey" = NXGQXM2347Y23234Q4;
"#createdDate" = "2013-05-22";
"#name" = ThirdApp;
"#platform" = Android;
}
);
}
This is method I have used.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[self convertDataIntoDictionary:responseData];
}
-(void)convertDataIntoDictionary:(NSData*)data{
NSDictionary *dictionary;
if (data.length>0) {
NSError *parsingDataError;
dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parsingDataError];
if (parsingDataError) {
// [ErrorAlert showError:parsingDataError];
NSString *recievedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data Conversion Error When Parsing: %#", recievedString);
}
}
NSLog(#"Data back from server\n %#",dictionary);
NSArray *applicationDetails = dictionary[#"application"];
}
I can not go further then this?
I would like to get All NAME of APPS in Array.
Any help would be appreciate.
The basics of parsing JSON is:
{ }- dis represents dictionary
( )- dis represents array
So in your JSON, there is a dictionary at the root and inside it has a key application which cbntains an Array.
NSArray *applicationArray = [dictionary objectForKey:#"application"];
NSMutableArray *mutableAppNamesArray = [[NSMutableArray alloc]init];
Inside this array there are three NSDictionary at every index:
for(NSDictionary *dict in applicationArray){
NSString *appName = [dict objectForKey:#"#name"];
NSLog(#"app name : %#", appName);
[mutableAppNamesArray addObject:appName];
}
NSArray * appNamesArray = [NSArray arrayWithArray:mutableAppNamesArray];
I think this is not a proper format for JSON. JSON objects usually contain ':' instead of '='
Example :-
{
products_id: "476",
products_model: "XOLO Play",
products_price: "15499.0000",
products_image: "xolo-play-play-t1000-.jpg",
products_date_available: null,
products_last_modified: "2013-08-04 06:04:11",
products_date_added: "2013-08-04 06:03:10",
manufacturers_id: "17",
products_status: "1",
products_rating: null,
category_id: "11"
},
{
products_id: "18",
products_model: "Nokia Lumia 820",
products_price: "8990.0000",
products_image: "samsung-galaxy-ace-duos-gsm-mobile-phone-large-1.jpg",
products_date_available: null,
products_last_modified: "2013-07-30 03:45:28",
products_date_added: "2013-01-23 00:52:00",
manufacturers_id: "2",
products_status: "1",
products_rating: "3",
category_id: "11"
},
But if you still need to parse it then you might try as below:
First get into the array
by NSDictionary *array = [allValues objectForKey:#"application"]; then each index to NSDictionary and then object for key. If its your server response than try to make it in the proper JSON format.

Resources