Break String that came from Json - iphone

I have a String that I got from a webserver which came in json format, but the string is huge with everything in it. I tried using the NSDICTIONARY but to no success. I was wondering what would be the best approach to break this string and add to different strings and eventually put it all in a class of strings. Thanks for the help! Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error=nil;
NSLog(#"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are
/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:#"ID"]; // for example
NSLog(#"ID Number: %#", ID);*/
Here is some of the log i get:
[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]

You are doing it wrong. Its a NSArray of NSDictionaries. So first you need to assign it to NSArray and then loop over it to get each individual NSDictionary. See below.
NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
NSLog(#"ID: %#", [record objectForKey:#"ID"]);
}

You'll probably be better off just using NSJSONSerialization if your app is targeted for at or over iOS 5.0:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
You might need to experiment with using NSArray vs. NSDictionary, etc., but this should be an overall simpler solution.

Try this :
NSArray *results = [returnString JSONValue];
for (int i=0; i<[results count];i++) {
NSDictionary *DetailDictonary=[results objectAtIndex:i];
NSString *strid=[DetailDictonary objectForKey:#"ID"];
NSString *strName=[DetailDictonary objectForKey:#"name"];
NSString *strBio=[DetailDictonary objectForKey:#"bio"];
// Or You can set it in Your ClassFile
MyClass *classObj=[[MyClass alloc] init];
classObj.strid=[DetailDictonary objectForKey:#"ID"];
classObj.strName=[DetailDictonary objectForKey:#"name"];
classObj.strBio=[DetailDictonary objectForKey:#"bio"];
[YourMainArray addObject:classObj]; //set YourClass to Array
[classObj release];
}

Related

How to format a ReturnString Array from a webService

I get a returnString from a WebService in iOS:
[
{"datum":"2013-07-24
09:38:43","nummer":"1017348010239480212208","anmerkung":"Elektronische
Auftragsdaten wurden vom Versender
\u00fcbermittelt"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Verteilung"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Verteilung"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Zustellung"},{"datum":"2013-07-24
09:26:06","nummer":"1017348010239480212208","anmerkung":"Empf\u00e4nger
nicht angetroffen - benachrichtigt"},{"datum":"2013-07-19
06:24:42","nummer":"1017348010239480212208","anmerkung":"Sendung in
Post-Empfangsbox eingelangt"}
]
the Objective C Code works fine:
#import "SBJson.h"
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
self.textfeld.text = [NSString stringWithFormat: #"%#", returnString];
I try to format the Response with NSMutableArray or NSArray and JSONValue but without success :
NSMutableArray *meinErgebnis = [responseString JSONValue];
NSLog(#"%#",[[meinErgebnis objectAtIndex:0] objectAtIndex:1]);
How to format the returnCode like that?
Nummer: 1017348010239480212208
Anmerkung: Sendung in Verteilung
Nummer: 1017348010239480212208
Anmerkung: Sendung in Post-Empfangsbox
You can obtain Data with following method,
id Data = [NSJSONSerialization JSONObjectWithData:fetchedData options:kNilOptions error:&error];
Then you can loop the data accordingly. For your example,
for(id object in Data)
{
NSLog(#"%#",[object valueForKey:#"nummer"]);
NSLog(#"%#",[object valueForKey:#"anmerkung"]);
}
The loop used above is of fast Enumeration type. Hope this helps.
Use following code for get all the values of nummer and anmerkung from your mutable array.
NSMutableArray *meinErgebnis = [responseString JSONValue];
for(int i = 0; i < meinErgebnis.count; i++)
{
NSLog(#"%#",[[meinErgebnis objectAtIndex:i] objectForKey:#"nummer"]);
NSLog(#"%#",[[meinErgebnis objectAtIndex:i] objectForKey:#"anmerkung"]);
}

iPhone:Adding multiple nsdictionaries into NSArray

I need to add multiple NSDictionaries into an NSArray to get a JSON message.I want to get this string.
This is my code:
for (int i=0;i<[ids count]; i++)
{
[dict setObject:[NSString stringWithFormat:#"%#",personName] forKey:#"customerName"];
NSArray *array = [NSArray arrayWithObject:cartDict];
[dict setObject:array forKey:#"OrderDetails"];
}
NSString *request1 = [dict JSONRepresentation];
//convert object to data
NSData *jsonData = [NSData dataWithBytes:[request1 UTF8String] length:[request1 length]];
//NSData* jsonData = [NSJSONSerialization dataWithJSONObject:req options:NSJSONWritingPrettyPrinted error:nil];
//print out the data contents
json1 = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
You are just changing the values in the same instance of the cartDict. If you want to have more than one cartDict in your array, alloc and init a new NSDictionary and then add that to the array (don't forget to release after if you aren't using ARC!).

JSON parsing issue

My code:
NSString *jsonString;
jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];
NSLog(#"%#",jsonString);
// Build an array from the dictionary for easy access to each entry
NSArray *places = [results objectForKey:#"description"];
I am not getting the result i wanted.
When I debug the code I am getting 2 key/value pair & 0 object for NSArray places.
It is correct that you have 2 key/value pairs. The top two keys intact are "predictions" and "status". So you must first of all extract predictions (it's an array):
NSArray *predictions = [results objectForKey:#"predictions"];
and then iterate over it; also note that "description" is a string and to get the places you must split it using the "," separator:
for(NSDictionary *aPrediction in predictions) {
NSString *description = [aPrediction objectForKey:#"description"];
NSArray *placesInDescription = [description componentsSeparatedByString:#","];
}
maybe you should use:
NSArray *places = [results valueForKey:#"predictions"];
Works for me without any problems with JSON Kit!
NSString *jsonString;
NSData *responseData = [NSData dataWithContentsOfURL: [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=solapur&sensor=true&key=AIzaSyC0K5UhV_BWmXhncIZEnbh-WG2RVQVgfdY"]];
jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString objectFromJSONString];
// Build an array from the dictionary for easy access to each entry
NSArray *places = [results valueForKey:#"predictions"];
NSLog(#"places %#", places);

How to read the JSON value on console in iphone

i have the following json value in console:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
this is my server api :#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"
//api takes 5 parameters .
when i post data to server api values are posted to server and i get the above response in json format.
i want to parse the above the JSON value that i get in the response and save in sqlite database.
i am doing this code to parse the above JSON value:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
You should check out some of the JSON parsers, my personal favourite is json-framework. After you've included one of them in your project, where you've got your JSON response from your server:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:#"Result"];
which will return your array of results (where each object in the array is an NSDictionary).
You can save this to a database with the help of a model class, Result
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:#"UserId"];
result. FirstName = [value objectForKey:#"FirstName"];
...
[results addObject:result];
[result release];
}
use the array of results to save it to the database.
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}

How to use JSONValue with NSMutableArray

here is my code and It doesn't work
NSError *theError = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.bbblllaaahhh.com"]];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.city = [[NSMutableArray arrayWithArray:[string componentsSeparatedByString:#"\""]] JSONValue];
And here is JSON text
[
{
"kanji_name":"\u30ac\u30fc\u30c7\u30f3\u30d5\u30a3\u30fc\u30eb\u30ba\u3000\u3068\u306d\u308a\u516c\u5712BigBell"
}
]
It reports in self.city line , What should I do ??
Yeah!! I completely fix it Here is My fix code
NSError *theError = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.blahblah.com"]];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [string JSONValue];
NSArray *jsonArray = [NSArray arrayWithArray:(NSArray *)[jsonDict valueForKey:#"kanji_name"]];
NSMutableString *text = [[NSMutableString alloc] init];
[text appendFormat:#"%#",[jsonArray objectAtIndex:0]];
self.city = [NSMutableArray arrayWithObject:text];
A couple of questions will be needed to help determine the answer to this problem.
First, can you place
NSLog(#"%#",data);
after the first line and
NSLog(#"%#", string);
after the second line and tell us what value it reports to the console? This will help determine if the problem is
1) That the server never returns any data or returns the wrong data and
2) If the data is correctly turned into a string. If either of these actions fails, it may cause an error in line 3.
Next, could you report what error the third line is giving? There are many possible problems. It could be that the string is not, in fact, proper JSON code and the JSON parser is crashing.
Line 3 looks like it has one obvious problem. First, you are splitting a string based on the "\" character, which seems like an unusual thing to do in this situation. But anyway, the order of operations will look like this:
#"a\b"
will be turned into
["a", "b"]
then the JSON parser will try to parse ["a", "b"], which will certainly cause an error.
At the very least, you will want to do something like,
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSArray or NSDictionary *parserResults = [string JSONValue];
// This will depend on what the actual JSON string returned from the server
// With an array, maybe something like
NSString *stringWithBackslash = [NSArray objectAtIndex:0];
// With a dictionary, maybe something like
NSString *stringWithBackslash = [NSDictionary objectForKey:#"backslashString"];
self.city = [NSMutableArray arrayWithArray:[stringWithBackslash componentsSeparatedByString:#"\""]];
Is self.city an NSMutableArray? The variable name makes it sound like it should be a string. In that case, you would actually want to do something like
NSMutableArray components = [NSMutableArray arrayWithArray:[stringWithBackslash componentsSeparatedByString:#"\""]];
// if the city is the first element of the array
self.city = [components objectAtIndex:0];
You will also want to check to make sure that components, for example, has more than element because that also might cause an error, if, for example, the server returned an error or there were no internet connection.