ios Twitter API JSON parsing - ios

I'm trying to parse the JSON string received by the Twitter API to get the user timeline.
I'm using Jastor to convert the JSON response to objective c objects.
Everything works fine until I try to parse the entities object
entities = {
hashtags =();
media = (
{
"display_url" = "pic.twitter.com/...";
"expanded_url" = "http://...";
id = ...;
"id_str" = ...;
indices =(
5,
25
);
"media_url" = "http://...";
"media_url_https" = "https://...";
sizes ={
large ={
h = 765;
resize = fit;
w = 1024;
};
medium ={
h = 448;
resize = fit;
w = 600;
};
small ={
h = 254;
resize = fit;
w = 340;
};
thumb ={
h = 150;
resize = crop;
w = 150;
};
};
type = photo;
url = "http://...";
}
);
urls =();
"user_mentions" = ();
};
Even if the JSON is not standard Jastor seems to parse all of it but this block due to the presence of "(" ")".
Do you know how to allow Jastor to parse this block as well? Or do I have to change library?
Thank you.

What's curious with the output of your question is that it is not a JSON formatted string. It looks like a nested combination of NSDictionary and NSArray objects which is typical when you convert a JSON string into Objective-C objects. When you NSLog this sort of object, the curly braces indicate NSDictionary objects and the parentheses indicate NSArray objects.
So, it just looks like you're displaying a typical, successfully parsed JSON object. You can decipher it as follows, assuming that the above output was generated by doing a NSLog of some NSDictionary called, say, jsonObject:
NSDictionary *entity = [jsonObject objectForKey:#"entities"];
NSArray *media = [entity objectForKey:#"media"];
NSDictionary *media0 = [media objectAtIndex:0];
NSString *display_url = [media0 objectForKey:#"display_url"];
NSArray *sizes = [media0 objectForKey:#"sizes"];
NSDictionary *size0 = [sizes objectAtIndex:0];
or, if using modern Objective C, simply:
NSDictionary *entity = jsonObject[#"entities"];
NSArray *media = entity[#"media"];
NSDictionary *media0 = media[0];
NSString *display_url = media0[#"display_url"];
NSArray *sizes = media0[#"sizes"];
NSDictionary *size0 = sizes[0];
etc.

Why not using the new feature in iOS 5.0 NSJSONSerialization, it converts JSON data to Objective C standarts like NSArray or NSDictionary.
NSString *stringURL = [NSString stringWithFormat:#"%#?%#", kTwitterApi, kParams];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:stringURL]];
request.HTTPMethod = #"GET";
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error%#", error.localizedDescription);
}else {
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&err];
NSLog(#"%#", json);
}
}];

Related

New to JSON API how to access the values in objective-c?

Below is my code to access the JSON API from Edmunds.com, this works perfectly to access the information I am just having trouble with accessing the key, value pairs.
NSURL *equipmentURL = [NSURL URLWithString: [NSString stringWithFormat:#"https://api.edmunds.com/api/vehicle/v2/styles/%#/equipment?fmt=json&api_key=%#", self.carID, apiKey]];
NSData *jsonData = [NSData dataWithContentsOfURL:equipmentURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.engineArray = [NSMutableArray array];
NSArray *equipmentArray = [dataDictionary objectForKey:#"equipment"];
for (NSDictionary *carInfoDictionary in equipmentArray) {
NSArray *attributes = [carInfoDictionary objectForKey:#"attributes"];
NSLog(#"%#", attributes);
}
In the NSLog from the above code shows this:
2016-11-03 10:21:26.029 CarWise[25766:1896339] (
{
name = "Engine Immobilizer";
value = "engine immobilizer";
},
{
name = "Power Door Locks";
value = "hands-free entry";
},
{
name = "Anti Theft Alarm System";
value = "remote anti-theft alarm system";
}
)
My main question is how can I access the name and value for each array? Let's say I want to create a UILabel that will have the string of one of the values?
Probably this will help
// Array as per the post
NSArray *attributes = (NSArray *)[carInfoDictionary objectForKey:#"attributes"];
// Loop to iterate over the array of objects(Dictionary)
for (int i = 0; i < attributes.count; i++) {
NSDictionary * dataObject = [NSDictionary dictionaryWithDictionary:(NSDictionary *)attributes[i]];
// This is the value for key "Name"
NSString *nameData = [NSString stringWithString:[dataObject valueForKey:#"name"]];
NSLog(#"Value of key : (name) : %#", nameData);
}

Any tools to beautify the nested NSDictionary result

Is there any tools, including online service and macOs app, to beautify the nested NSDictionary result like this?
{
id = 1;
testName = my name;
createDate = 20021023;
likeNumber = 0;
statusList = ({
appleId = 1;
orangeName = 81;
itsStatus = YES;
});
text = test;
type = Text;
},
I mean collapse(close and open) the tree nodes easily.
Currently ,there are many online tools for this purpose when it comes to JSON like jsonformatter.
As Fonix mentioned, the best way to convert NSDictionary to JSON and then use JSON tools for this purpose:
+(NSString *)dictionaryToJson:(NSDictionary *)dictionary {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
jsonString = [error localizedDescription];
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonString;
}

Setting data in correct JSON format using Array and Dictionary

Below is the model for which I have to set the data. I am using array and dictionary to achieve this, Here is the code which I tried. But its giving me the output which is invalid JSON.
One more thing I want to ask is why the log of an array starts and ends with small braces?
Any help would be much appreciated.
Code:
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
parameterName,#"parameterName",
parameterType, #"parameterType",
[NSNumber numberWithBool:parameterSorting],#"parameterSorting",[NSNumber numberWithBool:parameterSorting],
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:paramData];`
Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":"(
{
parameterName = anandShankar;
parameterOrdering = 1;
parameterSorting = 1;
parameterType = Text;
}
)","catalogMode":"xxxxxx"}}
Desired Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":[{
"parameterName" : "anandShankar",
"parameterOrdering" : 1,
"parameterSorting" : 1,
"parameterType" : "Text"
}],"catalogMode":"xxxxxx"}}
There is nothing wrong in it. in console or log round braces () indicates array. if it is showing round braces then it is array. you will never het [] square braces in console or log.
Update :
NSData *data = [NSJSONSerialization dataWithJSONObject:paramData options:kNilOptions error:nil];
and then send this data to server. it will in your desired json fromat
hope this will help :)
Try this code :
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
#"Object1",#"parameterName",
#"Object2", #"parameterType",
#'Object3',#"parameterSorting",#"Object4",
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
Add this lines :
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:paramData options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString); // it will print valid json
JSON
{
"rqBody":{
"catalogName":"",
"parameter":[
{
"parameterOrdering":"Object4",
"parameterName":"Object1",
"parameterType":"Object2",
"parameterSorting":51
}
],
"userId":"",
"catalogMode":""
}
}

How to create Array of Dictionaries from comma separated strings?

I am receiving comma separated string as below which is to be converted to array of dictionaries.I tried using [myString componentsSeparatedByString:#","]; which however gives a totally different output.What is the correct way of converting it?
NSString *cancellationStr ==> [{"cutoffTime":"0-2","refundInPercentage":"0"},{"cutoffTime":"2-3","refundInPercentage":"50"},{"cutoffTime":"3-24","refundInPercentage":"90"}]
NSArray *array = [cancellationStr componentsSeparatedByString:#","];
//Gives response like below
(
"[{\"cutoffTime\":\"0-2\"",
"\"refundInPercentage\":\"0\"}",
"{\"cutoffTime\":\"2-3\"",
"\"refundInPercentage\":\"50\"}",
"{\"cutoffTime\":\"3-24\"",
"\"refundInPercentage\":\"90\"}]"
)
The code to fetch and parse using a singleton HTTP class
NSString *urlString=[NSString stringWithFormat:#"%#%#sourceCity=%#&destinationCity=%#&doj=%#",BASE_URL,AVAILABLE_BUSES,source,destination,dateStr];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url= [NSURL URLWithString:urlString];
SuccessBlock successBlock = ^(NSData *responseData){
NSError *error;
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
bArray = [jsonDictionary objectForKey:#"apiAvailableBuses"];
};
FailureBlock failureBlock = ^(NSError *error){
NSLog(#"%#",error);
};
HTTPRequest *request = [[HTTPRequest alloc]initWithURL:url successBlock:successBlock failureBlock:failureBlock];
[request startRequest];
The above success block receives the string which then I am looking to convert.
NSString *cancellationStr = [[bArray objectAtIndex:rowIndex]valueForKey:#"cancellationPolicy"];
bObject.cancellationPolicy = [cancellationStr componentsSeparatedByString:#","];
NSLog(#"Cancellation Array : %#",bObject.cancellationPolicy);
So, "apiAvailableBusses" is an array of elements like this one:
{
"operatorId":196,
"operatorName":"Sahara Bus",
"departureTime":"6:45 PM",
"mTicketAllowed":false,
"idProofRequired":false,
"serviceId":"1602",
"fare":"450",
"busType":"Sahara Hitech Non A/c",
"routeScheduleId":"1602",
"availableSeats":29,
"partialCancellationAllowed":false,
"arrivalTime":"07:30 AM",
"cancellationPolicy":"[{\"cutoffTime\":\"12\",\"refundInPercentage\":\"0\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"50\"}]",
"commPCT":0.0,
"boardingPoints":[
{
"time":"09:05PM",
"location":"Ameerpet,Kaveri Kmakshi Travels,Beside RKS Mall,Ameerpet, Mr.Aman-9391830030.",
"id":"6"
},
{
"time":"09:15PM",
"location":"Punjagutta,Sai Ganesh Travels, Punjagutta, Mr.Aman-9391830030.",
"id":"2241"
},
{
"time":"09:30PM",
"location":"Lakdi-ka-pool,Sahara Travels,Hotel Sri Krishna Complex,Mr.Aman-9391830030.",
"id":"2242"
},
{
"time":"08:45PM",
"location":"ESI,Behind Bajaj Show Room, Near Nani Travels. Mr.Aman-9391830030.",
"id":"2287"
},
{
"time":"09:45PM",
"location":"Nampally,Near Khaja Travels, Nampally,Mr.Aman-9391830030.",
"id":"2321"
},
{
"time":"09:16PM",
"location":"Paradise,Near SVR Travels, Paradise,Mr.Aman-9391830030.",
"id":"2322"
},
{
"time":"10:00PM",
"location":"Afzalgunj,Sahar Travels,Mr.Aman-9391830030.",
"id":"2323"
},
{
"time":"09:00PM",
"location":"Secunderbad Station,Near Asian Travels.Mr.Aman-9391830030.",
"id":"2336"
}
],
"droppingPoints":null,
"inventoryType":0
}
The "cancellationPolicy" element is a string which is what is called "embedded JSON". (Why they did that in this case I haven't a clue.) This means that the string must be fed through NSJSONSerialization again. And to convert the NSString to NSData (to feed through NSJSONSerialization again) you need to first use dataWithEncoding:NSUTF8StringEncoding.

using json, read contents in objective c

I'm learning a very basic method to download data from a weather api.
Basically trying to follow a tutorial.
Using the URL, I am able to download the data in JSON format into a dictionary. Then put into an array.
My question now is how do I read the particular value of an item in the array.
For example, when I do an NSLOG of the array I get the following... I only cut/paste a couple as there are 55 items.
So my question is how do I grab a particular value our of this array?
2013-03-18 14:37:57.576 LocalWeatherV3[1220:c07] loans: {
UV = 2;
"dewpoint_c" = "-4";
"dewpoint_f" = 24;
"dewpoint_string" = "24 F (-4 C)";
"display_location" = {
city = "Jersey City";
country = US;
"country_iso3166" = US;
elevation = "47.00000000";
full = "Jersey City, NJ";
latitude = "40.75180435";
longitude = "-74.05393982";
state = NJ;
"state_name" = "New Jersey";
zip = 07097;
};
estimated = {
};
"feelslike_c" = 2;
"feelslike_f" = 35;
"feelslike_string" = "35 F (2 C)";
"forecast_url" = "http://www.wunderground.com/US/NJ/
here is a piece of the .m
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"current_observation"]; //2
NSLog(#"loans: %#", latestLoans); //3
// 1) Get the latest loan
//NSDictionary* loan = [latestLoans objectAtIndex:1];
NSInteger counter = [latestLoans count];
thanks in advance!!
so when I do this
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
and i mouse over the local watch, I see
json NSDictionary * 0x08d62d40
[0] key/value pair
key id 0x08d61cf0
value id 0x08d62100
[1] key/value pair
key id 0x08d62150
value id 0x08d633a0
then i do
NSArray* latestLoans = [json objectForKey:#"current_observation"]; //2
NSLog(#"loans: %#", latestLoans); //3
and one of the items I want is in "latestloans" which is where all that data shows up. so I cant figure out how to grab one of the items
Let's assume you're trying to grab the forecast url. It's as simple as:
// update this line
NSDictionary *latestLoans = [json objectForKey:#"current_observation"];
// url variable will contain the first forecast url in the array
NSString *url = [latestLoans objectForKey:#"forecast_url"];

Resources