I want to convert a specific string to json - ios

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

Related

converting NSJSON to NSDictionary and how to get values

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"];
}

Objective C parse JSON

I Have this result JSON below that i get from my wcf service which i want to iterate through in my ipad app.I use the code below to parse the result json but the app gives error. How can iterate through this dictionary and get the items.
IOS Code:
myArray = [NSMutableArray array];
// Do any additional setup after loading the view.
NSString* URL = #"http://www.unluapps.com/Service1.svc/ListTopReports";
NSDictionary *dictionary = [JSONHelper loadJSONDataFromURL:URL ];
NSString *result=[dictionary valueForKey:#"ListTopReportsResult"];
NSLog(#"%#",result);
/* for (NSString* key in result ) {
id value=[result objectForKey:key];
NSLog(#"%# -+",value);
}
*/
JSON:
{
ListTopReportsResult: [
{
AppUserID: null,
Author: "Joe Matthew",
Company: "Coca-Cola",
Country: "Poland",
CreationDate: "8/20/2014 4:32:00 AM",
EndDate: null,
ResearchReportID: "2",
Sector: "Soft Drinks",
Summary: "da ascon casmld lmasdlasd",
Title: "Can Coca-cola beat the market?",
URL: "2123123.pdf"
},
{
AppUserID: null,
Author: "martina pawlik",
Company: "Cimsa",
Country: "Poland",
CreationDate: "8/20/2014 4:31:00 AM",
EndDate: null,
ResearchReportID: "1",
Sector: "Cement",
Summary: "asd adas asd asdasd asdasdasd",
Title: "Poland's cement sector is on the rise",
URL: "1123123.pdf"
}
]
}
Try this:
NSArray *result=[dictionary valueForKey:#"ListTopReportsResult"];
Because in your JSON, there is an array for key ListTopReportsResult.
Hope this helps. :)
Try doing something like this. This is not the exact solution and you'll have to work around your way.
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
Now you have your data in the array and extract it out using objectForKey or valueForKey.You can use NSDictionary or NSArray as per your requirement.
Firstly get the array from the above code. Then extract out the image content like this :
_demoArray = [json valueForKey:#"yourKeyField"];
Now you have the values in your demoArray.
Hope this helps.

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;
} )

iOS: Parsing dictionaries from a string into NSMutableDictionary / NSMutableArray

Is there a fast way to parse dictionaries in iOS from a sting, with the format:
property1: value1
property2: [ property3: value3 ; property4: [property5: value5] ]
property6: "and so on"
The string would contain something like:
NSString *str = #"property1: value1 property2: [ property3: value3 ; property4: [property5: value5]] property6: "and so on" ";
and would generate a root NSMutableDictionary / NSMutableArray element, containing additional
NSMutableDictionary / NSMutableArray elements
Thanks in advance
why not using json format ?
replace this with this
[ {
] }
; ,
and you will be able to use jsonparser : NSJSONSerialization
No. That isn't any standard format. It looks like a bizarro version of JSON. If you want to parse this format, you'll need to either find some third-party parser or wrote one yourself.
Your JSON string is invalid. Please use http://jsonlint.com to verity if your JSON string is valid or not. Now, given your JSON is valid, this is how you can read string JSON into a NSDictionary:
NSString *strData = #"{\"property1\":\"value1\",\"property2\":{\"property3\":\"value3\",\"property4\":\"value4\"}}";
NSData *data = [strData dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);

Putting JSON into an Array

I'm a noob when it comes to requests and JSON. Inside my app I send to the server and get back stuff so I can use it of course. I tried looking up different things but none really seem to be what I'm looking for. So I'm getting back what seems to be formatted JSON. What I want to know how to do is put it into a NSMutable array. The way I get this JSON is by using AFNetworking's AFJSONRequestOperation.
My response looks like this.
{
id = 38;
name = "St. Martin Hall";
},
{
id = 40;
name = "Assumptions Commons";
},
{
id = 41;
name = "Vickroy Hall";
},
{
id = 42;
name = "St. Ann Hall";
},
{
id = 37;
name = "Duquesne Towers";
}
if your JSON format like {"mainKey":[{},{},...]}
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* dataArray = [json objectForKey:#"mainKey"]; //2
else your JSON format like [{},{},...]
NSError* error;
NSArray* dataArray = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
I think your format is case 2: [] Array of Object {}
Tutorial: http://www.raywenderlich.com/5492/working-with-json-in-ios-5
JSON:http://www.json.org
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.
This class is available in iOS 5.0+. If you're targetting older iOS version, have a look at a third-party JSON framework:
Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
If that's what you're getting back it's not JSON I'm afraid. It does look like Javascript in a way but it should be more like
[
{
"id" : 38,
"name" : "St. Martin Hall"
},
{
"id" : 39,
"name" : "Assumptions Commons"
}
]

Resources