Display json response in to UILabel - ios

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

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

How to convert following string to JSON?

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

How to export .JSON file using NSMutableDictionary?

I have NSMutableDictionary inside this values are present like this
{
0 = {
imageangle = "0.09630692";
imageheight = "129.0245";
imagepath = "assets-library://asset/asset.PNG?id=BD849AC4-EDF2-4E05-B5F8-F5EE34385A97&ext=PNG";
imagescalex = "85.48777";
imagescaley = "85.48777";
imagewidth = "129.0245";
mainheight = 282;
mainwidth = 316;
};
memes = {
alpha = 1;
alphaFont = 1;
blue = 1;
blueFont = 0;
green = 1;
greenFont = "0.5";
memestext = "Kishore kumar kumar ";
red = 0;
redFont = 1;
textheight = 34;
textscalex = 13;
textscaley = "30.5";
textwidth = 316;
};
}
Using this i like to export this dictionary in .json file.
After that i am converting into JSONSTRING:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dickeyjson options:NSJSONWritingPrettyPrinted error:&error];
NSString* aStr;
aStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
My Question:
Is it possible to export it as .json and store it to local storage?
You certainly can export a string to a .json file, and this would be an outline of a correctly error handling way to do so:
do {
let jsonString = "{\"what\":\"ever\"}"
let jsonFile = "file.json"
guard let docs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first else {
throw NSError(domain: "what-no-Documents-folder??", code: 1, userInfo: nil)
}
let path = NSURL(fileURLWithPath: docs).URLByAppendingPathComponent(jsonFile)
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
} catch {
fatalError("Writing failed!")
}
and to read it back in,
do {
let path = NSURL(fileURLWithPath: "same as for writing")
let jsonString = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {
fatalError("Reading failed!")
}
However, it is probable that you want to put this JSON back into a dictionary when reading, yes? In that case, there's no need to convert to JSON, you should just use NSDictionary's writeToURL method directly, using the same outline as above; as I don't believe there's any JSON-representable object not conforming to NSCoder and therefore archivable with writeToFile/writeToURL.
What exactly is the problem? You convert the dictionary to NSData using NSJSONSerialization. Then you write the NSData to a file using a variant of writeToFile: or writeToURL: There is no reason to go through NSString, it's just a waste of time, memory, and battery life.
To read the data, use dataWithContentsOfFile or dataWithContentsOfURL, and again NSJSONSerialization. If you use a mapped file, the NSData doesn't even use memory; that would be useful if your data is multiple megabytes.

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

Resources