I have below string:
{"list": {"array":[{"current_rate":20.0,"id":1, "name": "abc"},
{"current_rate":20.0,"id":2, "name": "xyz"}]}}
I want to convert above string into array like
[current_rate: 20.0, id: 1, name: abc]
I used componentSeperatedByString:#":".
But it gives problem when name field contain ":" string.
Is there any way to convert above string into array.
The string you have seems valid JSON. You may want to parse it:
NSData *data = [theString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
Then you can get the object using the objectForKey: and objectAtIndex: methods on the appropriate classes.
Related
- i'm trying to parse this string values with Objective-C.
NSString * str= #"MyDataCallBack({
"one": "john",
"two": "mark",
"three": "hanna"
});";
i want to get the value content by name. Please consider this pseudo code:
NSString * data = parse("one");
then it will output the value of "one"
NSLog(#"The data value is %#\n", data); // The data value is john
but i don't have any idea how to achieve that. Please help me to achieve
that and show me how that is done with code.
You can directly use the NSJSONSerialization to achieve this:
NSString * str= #"MyDataCallBack({\"one\": \"john\", \"two\": \"mark\", \"three\": \"hanna\"});";
str = [str stringByReplacingOccurrencesOfString:#"MyDataCallBack(" withString:#""];
str = [str stringByReplacingOccurrencesOfString:#");" withString:#""];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *ec = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"%#",ec[#"one"]);
Hope this helps!
I have to prepare a dictionary for serialization and then post it to server. Dictionary may have several other dictionaries as values for #"items" key. But some brackets interrupt. And server response me an error html.
NSMutableArray *a = [[NSMutableArray alloc]init];
for(int i = 0; i < [self.cartCopy count]; i++) {
NSString *itemNumber = [NSString stringWithFormat:#"%d", i + 1];
NSDictionary *tempDict = #{ itemNumber : #{
#"item_id" : [[self.cartCopy objectAtIndex:i]objectForKey:#"id"],
#"quantity" : [[self.cartCopy objectAtIndex:i]objectForKey:#"quantity"],
#"type" : [[self.cartCopy objectAtIndex:i]objectForKey:#"type"],
#"color_id" : #"0",
}
};
[a addObject:tempDict];
}
NSDictionary *dict = #{
#"date":oDate,
#"address":oAddress,
#"name":oName,
#"shipping_date":oShippingDate,
#"receiver_phone":oReceiverPhone,
#"customer_phone":oCustomerPhone,
#"total_price": oTotalPrice ,
#"additional_info": #"asd",
#"items": a
};
UPDATE: My NSLog of string after [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil] :
{"address":"asd",
"name":"asd",
"receiver_phone":"123",
"customer_phone":"123",
"total_price":"1",
"date":"2013-03-05 21:22:55",
"additional_info":"asd",
"items":[
{"1":{
"type":"2",
"color_id":"0",
"item_id":10,
"quantity":"3"
}
},
{"2":{
"type":"1",
"color_id":"0",
"item_id":74,
"quantity":"3"
}
}
],
"shipping_date":"2030-03-03 12:12:12"
}
I think the reason is square brackets. How can i delete them?
For example, it works perfectly with dictionary:
NSDictionary *dict = #{
#"date":oDate,
#"address":oAddress,
#"name":oName,
#"shipping_date":oShippingDate,
#"receiver_phone":oReceiverPhone,
#"customer_phone":oCustomerPhone,
#"total_price": oTotalPrice ,
#"additional_info": #"asd",
#"items": #{
#"1":#{
#"type":#"1",
#"color_id":#"0",
#"item_id":#"1",
#"quantity":#"1"
},
#"2":#{
#"type":#"1",
#"color_id":#"0",
#"item_id":#"1",
#"quantity":#"1"
}
}
};
In your example that works perfectly the items object is a dictionary with keys {1, 2}.
In your output JSON your items object is an array.
This array contains 2 objects, each one is a dictionary.
The first contains a single key {1}.
The second contains a single key {2}.
You just need to remove the array and use a dictionary instead to store these dictionaries.
That looks as if you want to send JSON to the server. You can create JSON data from your dictionary with
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
If you need it as a string:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
I've been having trouble finding out how to convert a JSON array into an NSArray.
I have a php script that creates an array that is converted into JSON which is then sent and stored into an NSString that looks like:
[1,2,3,4]
My problem is that I need to make that into an NSArray of ints. How would one do that?
Thanks!
You should look at the documentation of the NSJSONSerialization class.
You can hand it the NSData received from a remote call that is a string in JSON format and receive the array or dictionary it contains.
NSObject *o =[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
// other useful "options":
// 0
// NSJSONReadingMutableLeaves
// NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers
you should then check that o is of the type you expect for sanity purposes
If I wanted to quickly break that into an array I would do it like this:
NSString * jstring = #"[1,2,3,4]"; //your json string
jstring = [jstring stringByReplacingOccurrencesOfString:#"[" withString:#""];
jstring = [jstring stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray * intArray = [string componentsSeparatedByString:#","];
//you could create your int from the array like this
int x = [[intArray objectAtIndex:0]intValue];
Import the SBJson in your project (drag and drop it)
#import "SBJson.h"
Then where you receive the JSON response from the php file
NSArray *array = [responseString JSONValue];
I have a simple JSON string that looks like
(
{
ID = 1;
response = Yes;
}
)
And my NSDictionary is not pulling the objectForKey. The jsonArray is displaying correctly. My code:
hostStr = [[hostStr stringByAppendingString:post] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *hostURL = [NSURL URLWithString:hostStr];
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:hostURL];
self.jsonArray = [jsonString JSONValue];
[jsonString release];
NSLog(#"%#", jsonArray);
NSDictionary *infoDictionary = [self.jsonArray objectForKey:#"ID"];
NSLog(infoDictionary);
This is probably the case since you have completely invalid JSON (test it out at http://jsonlint.com/). Because you are missing the quotation marks in your JSON the elements won't match the id ID. All object names/keys need to be in quotation marks.
You're lucky that your framework interprets your invalid JSON (somehow) correctly so that you actually get an array or a dictionary. Because of this the result of NSLog will be correct.
Rewrite your JSON like this to get it working:
{
"ID": 1,
"response": "YES"
}
(Also be sure that jsonArray is a NSDictionary)
I could not find out how to insert a boolean value (to appear as key:true in the JSON string) in my NSDictionary:
NSMutableDictionary* jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue: YES forKey: #"key"];
The code above does not run (obviously because YES is not an object).
How can I accomplish this?
You insert booleans into a dictionary using NSNumber. In this case, you can use the literal expression #YES directly, together with a dictionary literal, to make this a one-liner:
NSDictionary *jsonDict = #{#"key" : #YES};
To encode it to JSON, use +[NSJSONSerialization dataWithJSONObject:options:error]:
NSError *serializationError;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:jsonDict
options:0 error:&serializationError];
if (!jsonData) {
NSLog(#"%s: error serializing to JSON: object %# - error %#",
__func__, jsonDict, serializationError];
}
+[NSNumber numberWithBool:] is the typical way to add a boolean to a NSDictionary.
With Objective-C literals, [NSNumber numberWithBool:YES] can be represented with just #YES,
You can create your dictionary like so:
NSDictionary *jsonDict = #{#"key":#YES};