NSJSONSerialization parsing not returning all values in response Array/ Dictionary - ios5

I am using native NSURLConnectionDelegate with NSJsonSerialization. I am getting the REST response but not all the values it contains.
I have this JSON response in web-browser :
{
"error" : {
"err_num" : 0,
"err_message" : ""
},
"company" : {
"id" : 1,
"name" : "company_string1"
},
"company" : {
"id" : 7,
"name" : "company_string2"
},
"company" : {
"id" : 19,
"name" : "company_string3"
},
"company" : {
"id" : 13,
"name" : "company_string4"
},
"company" : {
"id" : 14,
"name" : "company_string5"
}
}
I am using NSURLConnection asynchronously and implement
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
} // receivedData is NSMutuableData initialized before
and in connectionDidFinishLoading I do:
NSMutableDictionary *array = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingMutableContainers error:&error];
When I log, I get
{
"err_message" = "";
"err_num" = 0;
}
{
id = 14;
name = "company_string5";
}
If I use NSJSONReadingAllowFragments I get
{
"err_message" = "";
"err_num" = 0;
}
{
id = 1;
name = company_string1;
}
Also checked NSDictionary, but I get same result. Is their some problem with the JSON here due to duplicate keys, is it only returning the last/first one? I also happened to check online, almost all says its a valid JSON. It is not giving any error!!

Well, the JSON is not an array (unless you left out some characters). You're presumably enumerating through the "array" and hence getting the dictionary values, without keys. NSLog the value of "array" itself and you will see all your keys there (in what is actually an NSDictionary).
(And if the keys really are all "company", you will only receive one "company" element. Multiple identical keys would be invalid JSON sent from the other end.)

Related

How to find special characters in a particular attribute of json data stored in mongodb using mongo query

how to search any special characters in a particular nested json object field. Am having a field which stores nested json data.
I need to write a MongoDB query to fetch all the names which is having special characters
Student collection:
Example:
{
_id:123
student: {
"personalinfo":{
"infoid": "YYY21"
"name": "test##!*"
}
}
}
I have tried few regular expressions but I am not sure how to loop in array elements
I expect it to print the infoid & name, which has special characters in the name field.
The following query can do the trick:
db.collection.distinct("student.personalinfo.name",{"student.personalinfo.name": { $not: /^[\w]+[\w ]*$/ } })
Data set:
{
"_id" : ObjectId("5d77a5babd4e75c58d59821d"),
"student" : {
"personalinfo" : {
"infoid" : "YYY21",
"name" : "test##!*"
}
}
}
{
"_id" : ObjectId("5d77a5babd4e75c58d59821e"),
"student" : {
"personalinfo" : {
"infoid" : "YYY21",
"name" : "Bruce##"
}
}
}
{
"_id" : ObjectId("5d77a5babd4e75c58d59821f"),
"student" : {
"personalinfo" : {
"infoid" : "YYY21",
"name" : "Tony"
}
}
}
{
"_id" : ObjectId("5d77a5babd4e75c58d598220"),
"student" : {
"personalinfo" : {
"infoid" : "YYY21",
"name" : "Natasha"
}
}
}
Output:
[ "test##!*", "Bruce##" ]
Try using below regex, it matches all unicode punctuation and symbols.
dbname.find({'student.name':{$regex:"[\p{P}\p{S}]"}})

how manipulate a NSDictionary generated by a json file in swift

I've a NSDictionary populated by a JSON file.
JSON file content (initially)
{
"length" : 0,
"locations" : []
}
I want add some elements in "locations". The elements have the below structure:
[
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
]
In next code I read de JSON File
let contentFile = NSData(contentsOfFile: pathToTheFile)
let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: nil, error: &writeError) as NSDictionary`
like you can see jsonDict contain the JSON's info but in a NSDictionary object.
At this point I can't add the elements mentioned before, I tried insert NSData, NSArray, Strings, and nothing results for me
After do this I want convert "final" NSDictionary in JSON again to save it in a file.
The "final" NSDictionary must be like this
{
"length" : 3,
"locations" : [
{
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
},
{
"name" : "some_name_2",
"lat" : "8.88889",
"long" : "9.456789",
"date" : "19/01/2015"
},
{
"name" : "some_name_3",
"lat" : "67.88889",
"long" : "5.456789",
"date" : "19/01/2015"
}
]
}
"length" control the index for new element
I have no more ideas to do this. thanks in advance
If you want to be able to modify the dictionary, you can make it mutable:
let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: .MutableContainers, error: &writeError) as NSMutableDictionary
The resulting NSMutableDictionary can be modified. For example:
let originalJSON = "{\"length\" : 0,\"locations\" : []}"
let data = originalJSON.dataUsingEncoding(NSUTF8StringEncoding)
var parseError: NSError?
let locationDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &parseError) as NSMutableDictionary
locationDictionary["length"] = 1 // change the `length` value
let location1 = [ // create dictionary that we'll insert
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
]
if let locations = locationDictionary["locations"] as? NSMutableArray {
locations.addObject(location1) // add the location to the array of locations
}
If you now constructed JSON from the updated locationDictionary, it would look like:
{
"length" : 1,
"locations" : [
{
"long" : "5.456789",
"lat" : "4.88889",
"date" : "19/01/2015",
"name" : "some_name"
}
]
}

How can i store request.responseData into NSdictionary for parsing

When i request to my web server it send me Json string in request.response.i want to store that json into NSDictionary for parsing and storing it into database.
My Json format is
{ "rowNumber" : 3,
[ { "Age" : "2 - 4 years old ",
"AndroidID" : "2",
"Category" : "Chanson",
"Description" : "fourni",
"Size" : 3447196,
"Thumbnail" : null,
"Title" : "test",
"iTunesID" : "2",
"inactive" : false,
"product_id" : 2} ],
[ { "Age" : "2 - 4 years old ",
"AndroidID" : "3",
"Category" : "Chanson",
"Description" : "Animation ",
"Size" : 3447196,
"Thumbnail" : null,
"Title" : "Escargot",
"iTunesID" : "3",
"inactive" : false,
"product_id" : 3
} ]
}
IF i use this code to print String by string to NSlog it display fine but How i can i store that into NDdictionary ??
NSString *response = [[request responseString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
To store into dictionary i tried this code but this store my json in reverse order
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:request.responseData
options:kNilOptions
error:&error];
for(NSString *key in [json allKeys]) {
NSLog(#"%#",[json objectForKey:key]);
it store it into reverse order. Any help is appreciated.I am using ASIFormDataRequest for networking.
Your JSON is not valid.
I check at
http://jsonviewer.stack.hu/
http://jsonviewer.net/
Your array format is wrong. Read JSON syntax HERE
This is how it should be done:
{ "rowNumber" : 3,
"Data" : [ {
"Age" : "2 - 4 years old ",
"AndroidID" : "2",
"Category" : "Chanson",
"Description" : "fourni",
"Size" : 3447196,
"Thumbnail" : null,
"Title" : "test",
"iTunesID" : "2",
"inactive" : false,
"product_id" : 2
} ,
{
"Age" : "2 - 4 years old ",
"AndroidID" : "3",
"Category" : "Chanson",
"Description" : "Animation ",
"Size" : 3447196,
"Thumbnail" : null,
"Title" : "Escargot",
"iTunesID" : "3",
"inactive" : false,
"product_id" : 3
} ]
}
Then to store JSON data, I recommend you using my technique HERE. Proper way and quite a beast
Json is parsed and output is NSArray or NSDicitonary
You added wrong json.Not proper format
NSdictionary doesn't have an order as you say.It is a key-value pair mechanism.That is it stores as a value for a key using setObject:ForKey: method and gives the value back when asked with same key used to set the value using objectForKey: method

iphone : How to get Address from json request?

I am trying to get this address = "8198 Snouffer School Rd, Gaithersburg, MD 20879, USA"
from this json request but could not successful to do it.
{
"name": "39.165110,-77.168550",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [ {
"id": "p1",
"address": "8198 Snouffer School Rd, Gaithersburg, MD 20879, USA",
"AddressDetails": {
"Accuracy" : 8,
"Country" : {
"AdministrativeArea" : {
"AdministrativeAreaName" : "MD",
"Locality" : {
"LocalityName" : "Gaithersburg",
"PostalCode" : {
"PostalCodeNumber" : "20879"
},
"Thoroughfare" : {
"ThoroughfareName" : "Snouffer School Rd"
}
}
},
"CountryName" : "USA",
"CountryNameCode" : "US"
}
},
"ExtendedData": {
"LatLonBox": {
"north": 39.1661825,
"south": 39.1634846,
"east": -77.1666884,
"west": -77.1693864
}
},
"Point": {
"coordinates": [ -77.1685611, 39.1650977, 0 ]
}
} ]
}
I have extracted Code from status but could not understand how to extract address.
NSArray* Status = [(NSDictionary*)[responseString JSONValue] objectForKey:#"Status"];
NSString *code = [Status objectForKey:#"code"];
NSArray* Placemark = [(NSDictionary*)[responseString JSONValue] objectForKey:#"Placemark"];
NSString *address = [Placemark objectForKey:#"address"]; // got error at this line.
It's an Array not the JSON Object.
try
NSString *address = [[Placemark objectAtIndex:0] objectForKey:#"address"]];
It looks like the placemark entry returns an array, not a dictionary (see the square brackets?).
PS: Please use small starting letters for your variables - otherwise they look like classes:-).
#Azhar :- Try this -- id
i.e
id Status = [(NSDictionary*)[responseString JSONValue] objectForKey:#"Status"];
id code = [Status objectForKey:#"code"];
id Placemark = [(NSDictionary*)[responseString JSONValue] objectForKey:#"Placemark"];
id address = [Placemark objectForKey:#"address"];
and find the desired key.

How to extract the distance from a Google Directions JSON file on the iphone

I am having a really hard time extracting a single value I need from a JSON file I get from a Google Directions request.
After sending the request, I get something like that:
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 31.831330,
"lng" : 34.834710
},
"southwest" : {
"lat" : 31.25299000000001,
"lng" : 34.653460
}
},
"copyrights" : "Map data ©2012 Mapa GISrael",
"legs" : [
{
"distance" : {
"text" : "85.6 km",
"value" : 85613",
},
But the only thing I want is the distance value (routes/legs/distance/value),
does any one know how to extract this value from the JSON file?
First of all, that doesn't seem like well formatted JSON, there is a trialing " after the value of the distance.
Most JSON frameworks will give you the objects in the most appropriate type. Dictionaries will be converted to NSDictionary and a list will be converted to an NSArray.
To get the route distance in the above JSON you'd parse the JSON into an NSDictionary using one of the many libraries out there, then you'd do something like this:
NSNumber *distance = [[[[[[parsedDict objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"distance"] objectForKey#"value"];
See if that works.