converting NSJSON to NSDictionary and how to get values - ios

This is a NSJSON from response.
[{"code":"000","msg":"normal","data":
[{"_master_id":"",
"_locale":"kr",
"c_url":"http://###.co.kr/##",
"c_server_ip":"###.co.kr",
"c_server_port":"#####",
.........
}]
}]
and I converted this NSJSON to NSDictionary using this
NSDictionary *recivedDictionary = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
then it become this
[{
code = 000;
data = (
{
"_locale" = kr;
"_master_id" = "";
"c_url" = ####
.....
}
);
msg: ####;
}]
The double quotes are gone.
I want to get the data from the dictionary, but I can't get values from the dictionary using
let RESP_DATA : NSDictionary? = foo.object(forKey: "data") as?NSDictionary
RESP_DATA == nil, true
How can i get "data" from the dictionary??.. Thank you

use this
NSDictionary * recivedDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e][0]["data"][0];
if (recivedDictionary.count > 0 ) {
NSString * master_id = recivedDictionary["_master_id"];
}

Related

I want to convert a specific string to json

server response
-> NSString : { key1 = value1 }{ key2 = value2 }{ key3 = value3 }
How do I convert it to json?
What should I do?
I think what you are looking for is something like this , but im not suer if you can use = isntead of :
NSString *stringValue =#"[{ \"Key1\":\"Value1\" },{ \"Key2\":\"Value2\" },{ \"Key3\":\"Value3\" }]";
NSLog(#"StringValues from Server=%#", stringValue);
// Convert to JSON object:
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[stringValue dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
NSLog(#"jsonObject=%#", jsonObject);
If this is not what you want try to give us some code and explain how you want it done

JSON Parsing Issue

Hello I am new to iOS development. I am trying to parse a JSON response. Below is the top part of the response:
Table =
{
Rows = {
results = (
{
Cells = {
results = (
{
Key = Rank;
Value = "6.251145362854";
ValueType = "Edm.Double";
"__metadata" = {
type = "SP.KeyValue";
};
},
{
Key = DocId;
Value = 978473;
ValueType = "Edm.Int64";
"__metadata" =
{
type = "SP.KeyValue";
};
},
{
Key = WorkId;
Value = 978473;
ValueType = "Edm.Int64";
"__metadata" = {
type = "SP.KeyValue";
};
},
{
Key = Title;
Value = "Vneea Ready!";
ValueType = "Edm.String";
"__metadata" =
{
type = "SP.KeyValue";
};
},.........................
Now I am using
NSError *error;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSDictionary *results = jsonObject[#"Table"][#"Rows"][#"results"];
So I was able to refine it until here, but then I use
NSDictionary *results = jsonObject[#"Table"][#"Rows"][#"results"][#"Cells"];
When I am going further for Cells and results it is giving me Empty element Error,
After referring to this post JSON parsing using NSJSONSerialization in iOS, it seems like "(" means an array in the response, but it is not working for me. Can someone help me, please?
results is an array, not a dictionary, so you cannot access its contents by name. Your JSON doesn't look well formed, though, because Key should be a string ("Title" not Title).
Each element in the results array is a dictionary, so to get the Value that corresponds to Title you can use
NSArray *results=jsonObject[#"Table"][#"Rows"][#"results"];
NSDictionary *result=[results objectAtIndex:0]; // access the first result
for (NSDictionary *result in results) {
if ([result[#"Key"] isEqualToString:#"Title"]) {
NSLog(#"The value of Title is %#",result[#"Value"]);
break;
}
}

Convert text into json in Objective c

I have a string that I want to convert it into JSON in iOS but it is returning nil when I'm parsing it using jsonkit. My string format is as follows.
[
{ index:0, title:ARPPU },
{ index:1, title:ARPU },
{ index:2, title:Conversion },
{ index:3, title:DAU },
{ index:4, title:DAU },
]
Any one have idea how I can convert into a JSON object? Any help is appreciated.
The problem I would see here is your JSON string is invalid. Validate your JSON here
Try this
NSString *strJson = #"[{\"index\": \"0\",\"title\": \"ARPPU\"}]";
id jsonObj = [NSJSONSerialization JSONObjectWithData:[strJson dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers error:nil];
This worked for me.
Convert your string to NSData with NSUTF8Encoding and do a JSONSerialisation to make it JSON
// Converting Your String to NSData
NSString *myString=#"[
{ index:0, title:ARPPU },
{ index:1, title:ARPU },
{ index:2, title:Conversion },
{ index:3, title:DAU },
{ index:4, title:DAU },
]";
// Converts the string to Data
NSData* data = [myString dataUsingEncoding:NSUTF8StringEncoding];
// Does JSONSerialisation and convert the data into JSON
NSDictionary*dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Prints here the JSON
NSLog(#"Dict value==%#",dict);
First fix the JSON string, see Introducing JSON and W3Schools.
Then it is a JSONstring representation.
Convert to NSData and use JSONObjectWithData:options:error:
NSString *JSONStringRepresentation= #"["
#"{ \"index\":0, \"title\":\"ARPPU\" },"
#"{ \"index\":1, \"title\":\"ARPU\" },"
#"{ \"index\":2, \"title\":\"Conversion\" },"
#"{ \"index\":3, \"title\":\"DAU\" },"
#"{ \"index\":4, \"title\":\"DAU\" },"
#"]";
NSData *JSONAsData = [JSONStringRepresentation dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *JSONAsArrayObject = [NSJSONSerialization JSONObjectWithData:JSONAsData options:0 error:&error];
NSLog(#"JSONAsArrayObject: %#", JSONAsArrayObject);
NSLog output:
JSONAsArrayObject: (
{
index = 0;
title = ARPPU;
},
{
index = 1;
title = ARPU;
},
{
index = 2;
title = Conversion;
},
{
index = 3;
title = DAU;
},
{
index = 4;
title = DAU;
} )

How to parse nested JSON objects?

I get the JSON format like this:
stream( { posts: [{CHANNEL: {ios: "(format=m3u8-aapl).m3u8"} }]})
What I want to get is an array for the "ios".
This is my code:
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSArray *ios_data = [[[dataDict objectForKey:#"posts"] objectForKey:#"CHANNEL"] objectForKey:#"ios"];
NSLog(#"%#",ios_data);
dict = [NSDictionary dictionaryWithObjectsAndKeys:ios_data, ios,nil];
}
but it return in NULL, what the problem of it?
Your "JSON":
stream( { posts: [{CHANNEL: {ios: "(format=m3u8-aapl).m3u8"} }]})
Is not JSON. You can try running it through a validator like http://jsonlint.com/ to test it out.
Also, you should create an NSError reference to pass in instead of nil so NSJSONSerialization can vend you an error object. This will help in your debugging.
Here is an example of what your data would look like if it were valid JSON:
{
"stream": [
{
"posts": [
{
"CHANNEL": {
"ios": "(format=m3u8-aapl).m3u8"
}
}
]
}
]
}
(I spaced it out to be more legible, but the spacing is unnecessary for parsing.)
Once you have your array holding 'posts' you can drill down like this:
NSArray *fileData = [myDic1 valueForKeyPath:#"posts.CHANNEL"];
and then access like this:
for (int i=0; i < [clientFileData count]; i++) {
NSDictionary *myDictionary = [fileData objectAtIndex:i];
]
Also, unless I am wrong, your JSON file seems incorrectly formatted.
Get your response like:
NSDictionary *dictionaryData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Correct JSOn should be like this
{
"posts":[
{
"CHANNEL":{
"ios":"(format=m3u8-aapl).m3u8"
}
}
]
}
Get the correct format of JSON and then try to parse it. And one thing you were doing wrong is POST is an array.

JSon parsing error IOS with empty object key

Hi I have this JSON I'm trying to parse using NSDictionary and trying to get the values as mentioned . but the problem is i do not get a key when i further go into the JSON is there any way to remove this key to go more deep.
NSDictionary *Allinfo = [json objectForKey:#"Collection"];//I go into "Collection"
NSLog(#"All with response array: %#", Allinfo);
NSDictionary *datainfo = [Allinfo objectForKey:#"contact"];//i go into "contact"
after which i get
Data : (
{
attributeList = {
attribute = (
{
name = "display-name";
value = "tel:+";
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
},
{
attributeList = {
attribute = (
{
name = "display-name";
value = bob;
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
}
)
This starts from a { and i do not get a key for the next object so that i can get the values inside the JSOn
Is there any easier way to remove this or any other so that i can get values like name and value and store them in an array.
Thanks in advance
You have keys for all.
In fact you seem to get confused on array which is a part of attribute.
The outermost key is Data which contains array.
For each object of the array you have :
The first key is attributeList & contactD.
The value of attribute key is an array of 3 values. Each array contains key value pairs. keys are name & value.
I am not sure from where you got [Allinfo objectForKey:#"contact"]. Try to parse like below..
NSDictionary *Allinfo = [json objectForKey:#"Collection"];
NSArray *dataArray = [Allinfo objectForKey:#"Data"];
for(NSDictionary *dic in dataArray)
{
NSDictionary *attributeList=[dic objectForKey:#"attributeList"];
NSArray *attributeArray=[attributeList objectForKey:#"attribute"];
NSString *resourceURLString=[attributeList objectForKey:#"resourceURL"];
NSString *contactIdString=[dic objectForKey:#"contactId"];
for(NSDictionary *attributeDic in attributeArray)
{
NSString *nameString=[attributeDic objectForKey:#"name"];
NSString *valueString=[attributeDic objectForKey:#"value"];
}
}
You can use the following method for this
NSError *e = nil;
NSArray *itemArray = [NSJSONSerialization JSONObjectWithData:[response dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (!itemArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in itemArray) {
//Your Data
}
}

Resources