Hello guys i am facing problem related to convert string to json.
Here is my String :
[
{
"SCHEME_NAME": "FUG RSA SCHEME",
"Investment_Value": -46719.00201558,
"Bid_Price": 2.2566,
"Total_Contributions": 0,
"Growth": -46719.00201558,
"INVESTOR_ID": 5613,
"PFA_SCHEMEID": 1
},
{
"MONTH_NAME": "Balance as at 07-07-2016",
"EMPLOYEE_CONTRIBUTION": 3433764.77,
"EMPLOYER_CONTRIBUTION": 4381387.29,
"TOTAL_VALUE": 7815152.06,
"TOTAL_UNITS": 2782788.3885,
"TOTAL_FEE": 0,
"TOTAL_CONTRIBUTION": 7815152.06,
"Voluntary": "0.00"
},
{
"MONTH_NAME": "July 2016",
"EMPLOYEE_CONTRIBUTION": 0,
"EMPLOYER_CONTRIBUTION": 0,
"TOTAL_VALUE": 0,
"TOTAL_UNITS": -20703.2713,
"TOTAL_FEE": 0,
"TOTAL_CONTRIBUTION": 0,
"Voluntary": "0.00"
}
]
How to convert it into JSON?
Please help me.
Try this:
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:&error];
JSON is nothing but pairs of key/value pairs enclosed with an enclosed {} braces but you're missing one. You need one more enclosing root {} curly braces and specify key for your array, currently I've specified response, as per your requirement, then the JSON is valid.
{
"response": [
...
]
}
and then you can convert it with what #SaintThread has mentioned.
It is already in JSON format.I tried to convert string to json.I got it.But the result is same as what it is in question.
When convert string to json it should be in \"Key\":\"Value\" or \"Key\":Value
NSString *str=#"[{\"SCHEME_NAME\":\"FUG RSA SCHEME\",\"Investment_Value\":-46719.00201558,\"Bid_Price\":2.2566,\"Bid_Price\":\"2.2566\",\"Total_Contributions\":0,\"Growth\":-46719.00201558,\"INVESTOR_ID\":5613,\"PFA_SCHEMEID\":1},{ \"MONTH_NAME\": \"Balance as at 07-07-2016\",\"EMPLOYEE_CONTRIBUTION\": 3433764.77,\"EMPLOYER_CONTRIBUTION\": 4381387.29,\"TOTAL_VALUE\": 7815152.06,\"TOTAL_UNITS\": 2782788.3885,\"TOTAL_FEE\": 0,\"TOTAL_CONTRIBUTION\": 7815152.06,\"Voluntary\": \"0.00\"},{\"MONTH_NAME\": \"July 2016\",\"EMPLOYEE_CONTRIBUTION\": 0,\"EMPLOYER_CONTRIBUTION\":0,\"TOTAL_VALUE\":0,\"TOTAL_UNITS\": -20703.2713,\"TOTAL_FEE\": 0,\"TOTAL_CONTRIBUTION\": 0,\"Voluntary\": \"0.00\"}]";
NSData *dataStr = [str dataUsingEncoding:NSUTF8StringEncoding];
id jsonData = [NSJSONSerialization JSONObjectWithData:dataStr options:0 error:nil];
NSLog(#"The converted string to json is %#",jsonData);
Now the Printed result is
The converted string to json is (
{
"Bid_Price" = "2.2566";
Growth = "-46719.00201558";
"INVESTOR_ID" = 5613;
"Investment_Value" = "-46719.00201558";
"PFA_SCHEMEID" = 1;
"SCHEME_NAME" = "FUG RSA SCHEME";
"Total_Contributions" = 0;
},
{
"EMPLOYEE_CONTRIBUTION" = "3433764.77";
"EMPLOYER_CONTRIBUTION" = "4381387.29";
"MONTH_NAME" = "Balance as at 07-07-2016";
"TOTAL_CONTRIBUTION" = "7815152.06";
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "2782788.3885";
"TOTAL_VALUE" = "7815152.06";
Voluntary = "0.00";
},
{
"EMPLOYEE_CONTRIBUTION" = 0;
"EMPLOYER_CONTRIBUTION" = 0;
"MONTH_NAME" = "July 2016";
"TOTAL_CONTRIBUTION" = 0;
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "-20703.2713";
"TOTAL_VALUE" = 0;
Voluntary = "0.00";
}
)
Then When I get the data into array
NSArray *arrJson = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
NSLog(#"The arrjson is %#",arrJson);
The printed result is
The arrjson is (
{
"Bid_Price" = "2.2566";
Growth = "-46719.00201558";
"INVESTOR_ID" = 5613;
"Investment_Value" = "-46719.00201558";
"PFA_SCHEMEID" = 1;
"SCHEME_NAME" = "FUG RSA SCHEME";
"Total_Contributions" = 0;
},
{
"EMPLOYEE_CONTRIBUTION" = "3433764.77";
"EMPLOYER_CONTRIBUTION" = "4381387.29";
"MONTH_NAME" = "Balance as at 07-07-2016";
"TOTAL_CONTRIBUTION" = "7815152.06";
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "2782788.3885";
"TOTAL_VALUE" = "7815152.06";
Voluntary = "0.00";
},
{
"EMPLOYEE_CONTRIBUTION" = 0;
"EMPLOYER_CONTRIBUTION" = 0;
"MONTH_NAME" = "July 2016";
"TOTAL_CONTRIBUTION" = 0;
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "-20703.2713";
"TOTAL_VALUE" = 0;
Voluntary = "0.00";
}
)
Converting NSString to JSON
datasting to json
try this online json viewer:
http://jsonviewer.stack.hu/
You can format and view it online
Here is a format
[
{
"SCHEME_NAME": "FUG RSA SCHEME",
"Investment_Value": -46719.00201558,
"Bid_Price": 2.2566,
"Total_Contributions": 0.00,
"Growth": -46719.00201558,
"INVESTOR_ID": 5613,
"PFA_SCHEMEID": 1
}
,
{
"MONTH_NAME": "Balance as at 07-07-2016",
"EMPLOYEE_CONTRIBUTION": 3433764.77,
"EMPLOYER_CONTRIBUTION": 4381387.29,
"TOTAL_VALUE": 7815152.06,
"TOTAL_UNITS": 2782788.3885,
"TOTAL_FEE": 0.00,
"TOTAL_CONTRIBUTION": 7815152.06,
"Voluntary": "0.00"
},
{
"MONTH_NAME": "July 2016",
"EMPLOYEE_CONTRIBUTION": 0.00,
"EMPLOYER_CONTRIBUTION": 0.00,
"TOTAL_VALUE": 0.00,
"TOTAL_UNITS": -20703.2713,
"TOTAL_FEE": 0.00,
"TOTAL_CONTRIBUTION": 0.00,
"Voluntary": "0.00"
}
]
Related
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"];
}
My json Response is like this ..
{
sentdetails = (
{
coursename = "Course Two";
createddate = "05/12/2015 06:13 AM";
currentprice = "2.00";
"no_of_files" = 9;
queryid = 36;
querystatus = Open;
submissionid = TSAb13d585e;
testsaviornotes = None;
title = Test;
usernotes = rdgbv;
}
);
status = Sucess;}
Now I am trying to display json data which is forth one namely "no_of_files" into UILabel and my code is like ..
NSMutableArray * aryy=[NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
jsonDisplay = [aryy valueForKey:#"sentdetails"];
NSLog(#"%#",jsonDisplay);
NSLog(#"\n\n\n%#",aryy);
SentItemDetailViewController *viewController=[self.storyboard instantiateViewControllerWithIdentifier:#"SentItemDetailViewController"];
viewController.numberofFiles = [[jsonDisplay objectAtIndex:0]valueForKey:#"no_of_files"];
But the value for "num_of_files" can't store on UILable I don't know what's the problem behind that.
NSNumber * num = [[jsonDisplay objectAtIndex:0]valueForKey:#"no_of_files"];
viewController.numberofFiles.text = [num stringValue];
if numberofFiles is a UILabel you should write viewController.numberofFiles.text so:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
jsonDisplay = dict[#"sentdetails"];
NSLog(#"%#",jsonDisplay);
NSLog(#"\n\n\n%#",dict);
SentItemDetailViewController *viewController=[self.storyboard instantiateViewControllerWithIdentifier:#"SentItemDetailViewController"];
viewController.numberofFiles.text = [[jsonDisplay objectAtIndex:0][#"no_of_files"] stringValue];
Try
viewController.numberofFiles.text = [NSString stringWithFormat:#"%#",[[jsonDisplay objectAtIndex:0]valueForKey:#"no_of_files"]];
As I can notice that value for key no_of_files is not nsstring. Also need to give valuye to .text not label. :)
using Alamofire
first you have to convert data(NSData) into string .
var jsonString:String = ""
var parseDataToShow:Data?
#IBOutlet weak var lblToPrintDetails: UILabel!
Alamofire.request(url, method: .post, parameters: parameter)
.validate()
.responseJSON(completionHandler: { (response) in
debugPrint(response.result.value!)
// data form
let jsonData1 = response.data
jsonString = String(data: parseDataToShow!, encoding: .utf8)!
// you can print converted string data
print("JsonString = \(jsonString)")
self.lblToPrintDetails.text = jsonString
})
Using that code I'm able to get all the list of array.
Looking a lot of tutorial but I'm not able to get the var called "id" if the "name" isEqual to "Timeline Photos".
Code:
NSArray *feed =[result objectForKey:#"data"];
for (NSDictionary *dict in feed) {
NSLog(#"%#",dict);
}
Result (Example of the first two result):
2015-02-03 13:59:21.246 Project[708:29363] {
"can_upload" = 0;
count = 68;
"cover_photo" = 10200808394440000;
"created_time" = "2011-03-09T17:25:03+0000";
from = {
id = 10204248513160000;
name = "XX XX";
};
id = 1716972770000;
link = "https://www.facebook.com/album.php?..";
name = "Mobile Uploads";
privacy = everyone;
type = mobile;
"updated_time" = "2015-01-31T13:28:32+0000";
}
2015-02-03 13:59:21.247 Project[708:29363] {
"can_upload" = 0;
count = 11;
"cover_photo" = 4383404270000;
"created_time" = "2010-02-15T15:50:30+0000";
from = {
id = 10204248513160000;
name = "XX XX";
};
id = 1267183610000;
link = "https://www.facebook.com/album.php?...";
name = "Timeline Photos";
privacy = everyone;
type = wall;
"updated_time" = "2015-01-28T18:26:52+0000";
}
Try this:
NSArray *feed =[result objectForKey:#"data"];
for (NSDictionary *dict in feed) {
if ([dict[#"name"] isEqualToString:#"Timeline Photos"])
NSLog(#"%#",dict[#"id"]);
}
This will only print id when name is equal to Timeline Photos.
Actually, you are not working with an array, but with a dictionary.
Hope this helps.
Please help me. I want to post this json data which I created manually. And I'm getting error as Object reference not set to an instance of an object.
{
customerId = 81;
lstOrderItems = (
{
itemId = 149;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = (
{
attributeId = 135;
lstOrderAttributeValue = (
{
attributeValueId = 173;
},
{
attributeValueId = 174;
}
);
}
);
},
{
itemId = 129;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = (
{
attributeId = 119;
lstOrderAttributeValue = (
{
attributeValueId = 143;
},
{
attributeValueId = 144;
},
{
attributeValueId = 145;
},
{
attributeValueId = 155;
}
);
},
{
attributeId = 120;
lstOrderAttributeValue = (
{
attributeValueId = 146;
},
{
attributeValueId = 147;
}
);
},
{
attributeId = 124;
lstOrderAttributeValue = (
{
attributeValueId = 158;
},
{
attributeValueId = 165;
}
);
}
);
},
{
itemId = 132;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = ( );
},
{
itemId = 144;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = ( );
}
);
orderTotalPrice = 291;
outletId = 54;
}
To make your life a bit easier i won't suggest you to construct a json on your own, instead make a dictionary (or array, as per the need) and pass it to json serializer, it will construct a valid json for you (if possible).
Sample code:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:userFirstName, #"fname", userLastName, #"lname", nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"json : %#", json);
Output log:
2014-03-18 12:03:19.393 DesignMantic[1351:70b] json : {
fname = John;
lname = Doe;
}
Pass the constructed json to your service and you are free to invalid json issues.
Reference:
how to create json in objective-c
Hope it helps!
EDIT
Possibly, the data is not serialized to a valid json (may be because it is not convertable to json) and returned nil. You should check it first if the data is converted to json or not rty like this:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:infoDictionary options:NSJSONWritingPrettyPrinted error:&error];
if(jsonData && [NSJSONSerialization isValidJSONObject:jsonData])
{
NSString *postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *url = [NSString stringWithFormat:#"sqwip.ignivainfotech.net/api/customerapi/…"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
// Through error, since data sent for JSON serialisation is not convertible to json format
}
Your JSON Format is inValid
JSON Syntax Rules
JSON syntax is a subset of the JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
you must have your Format like below one
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.64,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
JSONLint is a great way to find out what's wrong with hand-coded JSON. There are both command-line and web-based versions.
If you were to paste the above JSON into JSONLint.com, you would see that one of the first mistakes you're making is using hash keys that aren't strings. Fix that, and there may be other errors you'll need to correct.
You'll learn the restrictions of JSON gradually and iteratively using a lint program like this. Good luck.
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;
} )