Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have problem with this json data:
{"return":"{\"productsList\":
[{\"BrandUID\":0,\"BrandName\":\"KAIREE\",\"ProductUID\":213,\"ProductName\":\"ANARKALI NET
WITH BANARASI
INNER\",\"Address\":\"\",\"Email\":\"\",\"Phone\":\"\",\"Price\":\"15000.00\",\"MainImage\":
\"http:\\\/\\\/tagin.xspl.in:8888\\\/images\\\/medium\\\/IMG_2635.JPG\",\"TagCount\":0},
{\"BrandUID\":0,\"BrandName\":\"KAIREE\",\"ProductUID\":245,\"ProductName\":\"SILK CHOODIDAR
SUIT\",\"Address\":\"\",\"Email\":\"\",\"Phone\":\"\",\"Price\":\"5195.00\",\"MainImage\":\
"http:\\\/\\\/tagin.xspl.in:8888\\\/images\\\/medium\\\/IMG_2696.JPG\",\"TagCount\":0},
{\"BrandUID\":0,\"BrandName\":\"ROOP SANGAM\",\"ProductUID\":124,\"ProductName\":\"KOTA
SILK\",\"Address\":\"\",\"Email\":\"\",\"Phone\":\"\",\"Price\":\"1050.00\",\"MainImage\":\"
http:\\\/\\\/tagin.xspl.in:8888\\\/images\\\/medium\\\/DSC_0181.JPG\",\"TagCount\":0}]}"}
can please some help me...I want array of image urls i.e of keys MainImage.
How can I do it using NSJSONSerialization
This looks like "nested JSON": the value of the "return" key is a string that itself
contains a complete JSON object. In that case you have to de-serialize twice,
something like this:
NSData *jsonData = ... // your JSON data
NSError *error;
NSDictionary *outerObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error: &error];
NSData *innerJson = [outerObject[#"return"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *innerObject = [NSJSONSerialization JSONObjectWithData:innerJson options:0 error:&error];
And now you can access the inner JSON object, for example:
NSArray *productsList = innerObject[#"productsList"];
NSArray *mainImages = [productsList valueForKey:#"MainImage"];
Try this
id mainDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&parseError];
Note:- here data is your response coming from server.
Now when you saw carefully above JSON data, the things wrapped inside {(curly bracket) are in the form of dictionary. And the things that are wrapped inside [(square bracket)are in the form of array.
So you can parse your data by following code,as our data is in maindict
NSArray *array = [[maindict valueForKey:#"return"]valueForKey:#"productsList"]];
Now when you print array you will get 3 elements in array.
Are you sure your JSON data is valid?
For example, this is valid JSON
{"\"key\"": "value"}
This is not:
{\"key\": "value"}
Please check the JSON data, i have modified, with extra "}"
{
"productsList": [
{
"BrandUID": 0,
"BrandName": "KAIREE",
"ProductUID": 213,
"ProductName": "ANARKALINETWITHBANARASIINNER",
"Address": "",
"Email": "",
"Phone": "",
"Price": "15000.00",
"MainImage": "http: //tagin.xspl.in: 8888/images/medium/IMG_2635.JPG",
"TagCount": 0
},
{
"BrandUID": 0,
"BrandName": "KAIREE",
"ProductUID": 245,
"ProductName": "SILKCHOODIDARSUIT",
"Address": "",
"Email": "",
"Phone": "",
"Price": "5195.00",
"MainImage": "http: //tagin.xspl.in: 8888/images/medium/IMG_2696.JPG",
"TagCount": 0
},
{
"BrandUID": 0,
"BrandName": "ROOPSANGAM",
"ProductUID": 124,
"ProductName": "KOTASILK",
"Address": "",
"Email": "",
"Phone": "",
"Price": "1050.00",
"MainImage": "http: //tagin.xspl.in: 8888/images/medium/DSC_0181.JPG",
"TagCout": 0
}
]
}
Related
I have the following JSon File,
[
{
"Var1": {
},
"Var2": "exemple 1",
"Var3": data,
"Var4": data,
"Var5": data,
"Var6": [
{
"Var7": {
},
"Var8": 25,
"Var9": 0,
"Var10": 0
},
{
"Var7": {
},
"Var8": 12,
"Var9": 1,
"Var10": 0
},
{
"Var7": {
},
"Var8": 12,
"Var9": 2,
"Var10": 0
}
],
"Var11": 300,
"Var12": data,
"Var13": 1,
"Var14": data,
"Var15": data,
"Var16": 2,
"Var17": data,
"Var18": data
},
]
I want to store the elements into an array so i could access them all. Should i now store every Variable in an array itself, and so have 16 arrays? and then access them? or is there any better way where i could store everything in one array?
I am using the following code to get one variable and get all its entities into one array :
NSString *strURL = [NSString stringWithFormat:#"MyUrl"];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSDictionary *json = [strResult JSONValue];
arrayToUse = [json valueForKeyPath:#"Var2"];
Using this code, i will have all the Var2 stored in one array :
arrayToUSe will have : [#"exemple 1", #"exemple 2 "];
Is there any better way than to store each entity with all its variable in an array ?
I desire to have : arrayToUse = [Var1,Var2,Var3,…];
I have string like this:
jsonArray:
{
d = "[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]";
}
I want to get the data between two square bracket(including square bracket) and then remove all the "\" to get my final string like this:
[
{
"Training_Code": "1234",
"Training_Duration": "2hrs",
"Training_Startdate": "14/02/201315: 00: 00",
"Training_Enddate": "14/02/201317: 00: 00",
"Trainer_ID": 1,
"Training_Location": "B-WingTrainingroom-4",
"Comments": "C#training",
"Keyword": "C#1234",
"NumberofDays": 1
},
{
"Training_Code": "4321",
"Training_Duration": "16",
"Training_Startdate": "17/02/201310: 30: 00",
"Training_Enddate": "17/02/201317: 30: 00",
"Trainer_ID": 2,
"Training_Location": "A-WingTrainingRoom-6",
"Comments": "Objective-C",
"Keyword": "Obj-C4321",
"NumberofDays": 2
}
]
How can I do this in objective-c? thanks.
Try using JSONKit(ref) or NSJSONSerialization (ref), they will give either an NSArray or NSDictionary, depending on the structure of the JSON string.
UPDATE:
d looks like a well formed JSON string, but where is it coming from? Is it a char[] (as mentioned in the coments above), NSString, or console output?
It looks from here that your first code listing is what gets printed to the console. Printing JSON strings to the console will usually print the escape characters (\). In your other post, you are assuming every response can be parsed into an array. It would be safer to store the returned object into an id first, then check its class:
id rawData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError
if ( jsonParsingError != nil ) {
// investigate the parsing error
}
else if ( [rawData isKindOfClass[NSDictionary class]] ) {
NSDictionary *dict = rawData;
// process dictionary
}
else if ( [rawData isKindOfClass[NSArray class]] ) {
NSArray *array = rawData;
// process array
}
else {
// some thing went completely wrong
}
You also do not indicate that you are checking any possible errors. Inspecting jsonParsingError will likely give clues as to what is going on.
Use nsstring method dataUsingEncoding to get a nsdata instance.
Use NSJSONSerialization
The string you wanted is same as you provided.
Since d is a string:
To remove "\" , you could this:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\" withString:#""];
Since the square brackets are at the front and the end, maybe you could do this:
[newString removeObjectAtIndex:0];
[newString removeObjectAtIndex:[newString count]-1];
first step is to get that string according to your situation and replace myString with your string.
Only if the source string contains one [ and ] each, then...
Use componentsSeparatedByString to split the source string with [.
Use componentsSeparatedByString to split the result (objectAtIndex:0) above with ].
I'm getting JSON data like following in a NS array:
It seems this is not valid JSON
jsonArray:
{
d = "[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]";
}
I want to change this to valid json like this:
[
{
"Training_Code": "1234",
"Training_Duration": "2hrs",
"Training_Startdate": "14/02/201315: 00: 00",
"Training_Enddate": "14/02/201317: 00: 00",
"Trainer_ID": 1,
"Training_Location": "B-WingTrainingroom-4",
"Comments": "C#training",
"Keyword": "C#1234",
"NumberofDays": 1
},
{
"Training_Code": "4321",
"Training_Duration": "16",
"Training_Startdate": "17/02/201310: 30: 00",
"Training_Enddate": "17/02/201317: 30: 00",
"Trainer_ID": 2,
"Training_Location": "A-WingTrainingRoom-6",
"Comments": "Objective-C",
"Keyword": "Obj-C4321",
"NumberofDays": 2
}
]
Note: I do not know, from where this "d" is comming...Plaese suggest keeping this in mind.
How can I change to valid json and insert this in my Sqlite DB? Thanks.
You can always inset it as plain text. If you want to manipulate JSON Strings, I recommend this. You can transform that String into a JKArray (which is the same than an Array). After that, iterate through your array and do your DB stuff (inserting into your table...)
Am I missing something? Maybe I need more info about what you want to do...
That's a string containing an encoded JSON array. You need to use a JSON decoder (batteries included as of iOS 5) to convert it into an NSArray, then walk it:
The following (untested) code should be about right:
// Assuming jsonArray is an object with an NSString property, d...
NSData *data = [jsonArray.d dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSArray *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:err];
// Check for errors.
for (NSDictionary *row in d) {
NSString *trainingCode = [row objectForKey:#"Training_Code"];
…
// Insert into SQLite here.
}
Note that, in recent versions of Xcode, you can write row[#"Training_Code"] instead of [row objectForKey:#"Training_Code"].
Parse your json using NSJSONSerialization and insert into database by mapping keys with your columns.
NSString *str = [[NSString alloc] initWithString:#"[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]"];
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
InfoLog(#"error: %#",jsonError);
NSArray *result = (NSArray*)allValues;
for(int i=0;i<[result count];i++)
{
NSDictionary *values = (NSDictionary*)[result objectAtIndex:i];
NSLog(#"Training_Code: %# Training_Duration: %#",[values objectForKey:#"Training_Code"],[values objectForKey:#"Training_Duration"]);
}
Now you are able to get values from NSDictionary and then simply add in your database.
What I'm trying to do is take a JSON feed and then loop through the results. However I keep getting a string instead of an array when I get the object from the dictionary. Any ideas on what I'm doing wrong?
Here's the JSON:
[
{
"_id": "4f6d9a7c1d0b4900010007ee",
"geo_triggers": [
{
"_id": "4fc3e5fdc7234e0001000002",
"location": [1,1],
"longitude": "1",
"latitude": "1",
"radius": 1,
"location_name": "Test 1"
},
{
"_id": "4fc61f3762f53f0001000043",
"location": [-71.057673,42.355395],
"longitude": "-71.057673",
"latitude": "42.355395",
"radius": 1000,
"location_name": "Test2"
}
]
}
]
Here's the Objective C Code:
const char* className = class_getName([result class]);
NSLog(#"Result is a: %s", className);
NSLog(#"%#", result); //string
NSArray* json = [result objectForKey:#"result"]; //should be an array of dictionaries
NSLog(#"JSON Output: %#", json);
const char* className1 = class_getName([json class]);
NSLog(#"yourObject is a: %s", className1);
And here's the output:
Result is a: __NSDictionaryI
2012-10-10 17:15:15.165 App[12980:19d03] {
result = "[{\"_id\":\"4f6d9a7c1d0b4900010007ee\",\"geo_triggers\":[{\"_id\":\"4fc3e5fdc7234e0001000002\",\"location\":[1.0,1.0],\"longitude\":\"1\",\"latitude\":\"1\",\"radius\":1,\"location_name\":\"Test 1\"},{\"_id\":\"4fc61f3762f53f0001000043\",\"location\":[-71.057673,42.355395],\"longitude\":\"-71.057673\",\"latitude\":\"42.355395\",\"radius\":1000,\"location_name\":\"Test2\"}]}]";
}
2012-10-10 17:15:15.166 App[12980:19d03] JSON Output: [{"_id":"4f6d9a7c1d0b4900010007ee","geo_triggers":[{"_id":"4fc3e5fdc7234e0001000002","location":[1.0,1.0],"longitude":"1","latitude":"1","radius":1,"location_name":"Test 1"},{"_id":"4fc61f3762f53f0001000043","location":[-71.057673,42.355395],"longitude":"-71.057673","latitude":"42.355395","radius":1000,"location_name":"Test2"}]}]
2012-10-10 17:15:15.166 App[12980:19d03] yourObject is a: __NSCFString
2012-10-10 17:15:15.166 App[12980:19d03] -[__NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xb331800
Your result variable points to a dictionary. The dictionary contains one key. That key is #"result". The value for that key is a string, #"[{\"_id\":\"4f6d9a7c1d0b4900010....
In other words, you haven't really deserialized your JSON. You need to take the value for key result and run it through a JSON deserializer.
First need to decode the result. The above is JSON so I would suggest doing this
If you don't already have it download JSONKit.h and include it in your project
Then you can either do
NSString* json = [result JSONString]; to see the output
OR
something like id jsonDict = [[JSONDecoder decoder] objectWithData:responseData];
After that you can do [jsonDict objectForKey:#"_id"]; ///etc
This question already has answers here:
Closed 10 years ago.
I am new in iPhone programming. Can anyone tell how parse the JSON string in iPhone?
I'm using JSON parsing in my application. This is my JSON data:
The JSON format is dz.
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
}
}
How can I do this parsing?
You can use some JSON-Framework, i.e.
https://github.com/stig/json-framework
Another solution would be NSRegularExpression
Save the json Data in a string and then use the regex
For example an Regex for the first line
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\"firstName\":[^\"]*\"([^\"]*)\"" options:0 error:&error];
NSArray *matches = [regex matchesInString:theString options:0 range:NSMakeRange(0, [theString length])];
NSTextCheckingResult *match = [matches objectAtIndex:0];
NSLog([theString substringWithRange:[match rangeAtIndex:1]]);
Explanation:
the regex looks for matches where you have "firstName": and then a variable number of signs except of "(because " inidicates where the data begins). ([^\"]) marks a specific range in the regex (so that you can extract it individually whit this line [theString substringWithRange:[match rangeAtIndex:1]]. [^\"] means every sign except "(because this is the end of data). I know this can be confusing at first. But If you take some time with it you will see that it's pretty easy.