After JSONSerialization decoded and as! cast to NSDictionary get data below.
{
language = {
A00001 = {
chineseSimplified = CIMB;
chineseTraditional = CIMB;
english = CIMB;
japanese = CIMB;
korean = CIMB;
};
};
}
How to access into nested NSDictionary?
I'm able to get one layer data through data["language"], somehow I can't access multiple layers like:
data["language"]["A00001"]["english"]
data["language"]?["A00001"]?["english"]?
data["language"]!["A00001"]!["english"]!
Xcode returns this error:
Type 'Any' has no subscript members
Reference similar question:
How to access deeply nested dictionaries in Swift
Accessing Nested NSDictionary values in Swift 3.0
How do I manipulate nested dictionaries in Swift, e.g. JSON data?
Try casting it into [String: [String: [String: String]]], which is a nested structure for Swift Dictionary.
let json = """
{
"language": {
"A00001": {
"chineseSimplified" : "CIMB",
"chineseTraditional" : "CIMB",
"english" : "CIMB",
"japanese" : "CIMB",
"korean" : "CIMB"
}
}
}
"""
if let jsonD = json.data(using: String.Encoding.utf8) {
do {
if let data = try JSONSerialization.jsonObject(with: jsonD, options: JSONSerialization.ReadingOptions.mutableLeaves) as? [String: [String: [String: String]]] {
print(data["language"]!["A00001"]!["english"]!)
}
} catch let error {
print(error.localizedDescription)
}
}
Here is another answer using Swift 4's Codable API. I thinks it's worth trying if your code needs type safety and you are sure the fields in JSON are consistent.
let json = """
{
"language": {
"A00001": {
"chineseSimplified" : "CIMB",
"chineseTraditional" : "CIMB",
"english" : "CIMB",
"japanese" : "CIMB",
"korean" : "CIMB"
}
}
}
"""
struct MyLanguages:Codable {
struct LanguageGroup: Codable {
struct Language:Codable {
var chineseSimplified: String
var chineseTraditional: String
var english: String
var japanese: String
var korean: String
}
var A00001: Language
}
var language: LanguageGroup
}
if let jsonD = json.data(using: String.Encoding.utf8) {
let jsonDecoder = JSONDecoder()
do {
let myLang = try jsonDecoder.decode(MyLanguages.self, from: jsonD)
print(myLang.language.A00001.chineseSimplified)
}
catch let err {
print(err.localizedDescription)
}
}
Related
I am fetching some data from my Objective C classes. Here is my 'dataArray' data:
Optional(<__NSArrayM 0x2818cff60>(
{
date = 1574164423;
shakeState = 1;
},
{
date = 1574164431;
shakeState = 1;
}
)
)
I have created a Modal class 'ShakeInfo', that contain date and shakeState value.
I just want to convert this Array into array of 'ShakeInfo' object. My problem is when I am trying to print 'dataArray[0]' then I am getting error :
error: <EXPR>:3:1: error: value of type 'Optional<NSMutableArray>' has no subscripts
dataArray[0]
How can I read this array value index wise. Please advise me.
Edited:
Here is my code after getting dataArray:
do {
let data = try JSONSerialization.data(withJSONObject: dataArray!)
let responseStr = String(data: data, encoding: .utf8)!
print(responseStr)//[{"date":"1574164424","shakeState":1},{"date":"1574164430","shakeState":1}]
var shakeInfoDetails = [ShakeInfo]()
//how to add 'responseStr' value in the shakeInfoDetails Modal Array
} catch {
print("JSON serialization failed: ", error)
}
let data = #"[{"date":"1574164424","shakeState":1},{"date":"1574164430","shakeState":1}]"#.data(using: .utf8)!
//Model
struct ModelRecord : Codable {
var date : String
var shakeState : Int
}
class Model {
var date : Date
var shakeState : Int
init?(record: ModelRecord) {
guard let secondsFrom1970 = Double(record.date) else {
return nil
}
date = Date(timeIntervalSince1970: secondsFrom1970)
shakeState = record.shakeState
}
}
//Decoding
let decoder = JSONDecoder()
do {
let records = try decoder.decode([ModelRecord].self, from: data)
let models = records.compactMap { Model(record: $0) }
}
catch {
print("Decoding Error: \(error)")
}
Answer to original question:
let a1 : NSMutableArray? = NSMutableArray(array: ["A", "B", "C"])
a1?.object(at: 2)
Please read about the following:
Optionals in Swift
Codable - https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
Arrays in Swift Standard Library
NSMutableArray defined in Foundation
I'm using the tableview to display the Two Json value but the problem is I cant add value into model struct to displaying into tableview using two Api's. i want to show percentage value in one of the cell label and
here is my json
[
{
"Percentage": 99.792098999,
}
]
my second json value
{
"Categories": [
"Developer",
"ios "
],
"Tags": [
{
"Value": "kishore",
"Key": "Name"
},
{
"Value": "2",
"Key": "office"
},
]
}
and i need show the Categories value in Categories label in tableview
value and key on tableview
here is my Struct
struct info: Decodable {
let Categories: String?
let Tags: String?
let Value: String?
let Key: String?
var Name: String?
let percentage: Double?
}
here its my code
var List = [info]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
print(json as Any)
guard let jsonArray = json as? [[String: Any]] else {
return
}
print(jsonArray)
for dic in jsonArray{
guard let per = dic["percentage"] as? Double else { return }
print(per)
}
and second json
if let array = json["Tags"] as? [[String: String]] {
for dict in array {
let key = dict["Key"]
let value = dict["Value"]
switch key {
case "office":
case "Name":
default:
break;
}
}
here is my cell for row indexpath
cell.Categories.text = list[indexpath.row].percentage
cell.Name.text = list[indexpath.row].name
cell.office.text = list[indexpath.row].office
Please use Swift 4 Codable protocol to decode the value from JSON.
//1.0 Create your structures and make it conform to Codable Protocol
struct Tags: Codable{
var Key: String
var Value: String
}
struct Sample: Codable{
var Categories: [String]
var Tags: [Tags]
}
In your method, perform below steps:
//2.0 Get your json data from your API. In example below, i am reading from a JSON file named "Sample.json"
if let path = Bundle.main.path(forResource: "Sample", ofType: "json") {
do {
let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
do {
//3.0 use JSONDecoder's decode method to decode JSON to your model.
let sample = try JSONDecoder().decode(Sample.self, from: jsonData)
//4.0 User the "sample" model to do your stuff. Example, printing some values
print("Sample.Category = \(sample.Categories)")
print("Sample.Name = \(sample.Tags[0].Value)")
print("Sample.Office = \(sample.Tags[1].Value)")
} catch let error {
print("Error = \(error)")
}
} catch {
// handle error
}
}
I prefer to use Codable all the time with JSON even for simpler types so for percentage I would do
struct ItemElement: Decodable {
let percentage: Double
enum CodingKeys: String, CodingKey {
case percentage = "Percentage"
}
}
and we need to keep these values in a separate array, declared as a class property
let percentageList: [Double]()
and json encoding would then be
let decoder = JSONDecoder()
do {
let result = try decoder.decode([ItemElement].self, from: data)
percentageList = result.map { item.percentage }
} catch {
print(error)
}
Similar for the second part
struct Item: Decodable {
let categories: [String]
let tags: [Tag]
enum CodingKeys: String, CodingKey {
case categories = "Categories"
case tags = "Tags"
}
}
struct Tag: Decodable {
let value, key: String
enum CodingKeys: String, CodingKey {
case value = "Value"
case key = "Key"
}
}
use a dictionary for the result, again as a class property
var values = [String: String]()
and the decoding
let decoder = JSONDecoder()
do {
let result = try decoder.decode(Item.self, from: data)
for item in result.tags {
values[item.key] = values.item.value
}
} catch {
print(error)
}
and then in the cell for row code
cell.Categories.text = percentageList[indexpath.row].percentage
cell.Name.text = values["name"]
cell.office.text = values["office"]
Note that this last code looks very strange since you don't have an array of name/office values judging by your json. Maybe you have simplified it some way but the code above is the best I can do with the information given even if it possibly wrong
I have classes like these:
class MyDate
{
var year : String = ""
var month : String = ""
var day : String = ""
init(year : String , month : String , day : String) {
self.year = year
self.month = month
self.day = day
}
}
class Lad
{
var firstName : String = ""
var lastName : String = ""
var dateOfBirth : MyDate?
init(firstname : String , lastname : String , dateofbirth : MyDate) {
self.firstName = firstname
self.lastName = lastname
self.dateOfBirth = dateofbirth
}
}
class MainCon {
func sendData() {
let myDate = MyDate(year: "1901", month: "4", day: "30")
let obj = Lad(firstname: "Markoff", lastname: "Chaney", dateofbirth: myDate)
let api = ApiService()
api.postDataToTheServer(led: obj)
}
}
class ApiService {
func postDataToTheServer(led : Lad) {
// here i need to json
}
}
And I would like to turn a Lad object into a JSON string like this:
{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}
EDIT - 10/31/2017: This answer mostly applies to Swift 3 and possibly earlier versions. As of late 2017, we now have Swift 4 and you should be using the Encodable and Decodable protocols to convert data between representations including JSON and file encodings. (You can add the Codable protocol to use both encoding and decoding)
The usual solution for working with JSON in Swift is to use dictionaries. So you could do:
extension Date {
var dataDictionary {
return [
"year": self.year,
"month": self.month,
"day": self.day
];
}
}
extension Lad {
var dataDictionary {
return [
"firstName": self.firstName,
"lastName": self.lastName,
"dateOfBirth": self.dateOfBirth.dataDictionary
];
}
}
and then serialize the dictionary-formatted data using JSONSerialization.
//someLad is a Lad object
do {
// encoding dictionary data to JSON
let jsonData = try JSONSerialization.data(withJSONObject: someLad.dataDictionary,
options: .prettyPrinted)
// decoding JSON to Swift object
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// after decoding, "decoded" is of type `Any?`, so it can't be used
// we must check for nil and cast it to the right type
if let dataFromJSON = decoded as? [String: Any] {
// use dataFromJSON
}
} catch {
// handle conversion errors
}
If you just need to do this for few classes, providing methods to turn them into dictionaries is the most readable option and won't make your app noticeably larger.
However, if you need to turn a lot of different classes into JSON it would be tedious to write out how to turn each class into a dictionary. So it would be useful to use some sort of reflection API in order to be able to list out the properties of an object. The most stable option seems to be EVReflection. Using EVReflection, for each class we want to turn into json we can do:
extension SomeClass: EVReflectable { }
let someObject: SomeClass = SomeClass();
let someObjectDictionary = someObject.toDictionary();
and then, just like before, we can serialize the dictionary we just obtained to JSON using JSONSerialization. We'll just need to use object.toDictionary() instead of object.dataDictionary.
If you don't want to use EVReflection, you can implement reflection (the ability to see which fields an object has and iterate over them) yourself by using the Mirror class. There's an explanation of how to use Mirror for this purpose here.
So, having defined either a .dataDictionary computed variable or using EVReflection's .toDictionary() method, we can do
class ApiService {
func postDataToTheServer(lad: Lad) {
//if using a custom method
let dict = lad.dataDictionary
//if using EVReflection
let dict = lad.toDictionary()
//now, we turn it into JSON
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict,
options: .prettyPrinted)
// send jsonData to server
} catch {
// handle errors
}
}
}
May this GitHub code will help you.
protocol SwiftJsonMappable {
func getDictionary() -> [String: Any]
func JSONString() -> String
}
extension SwiftJsonMappable {
//Convert the Swift dictionary to JSON String
func JSONString() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self.getDictionary(), options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let jsonString = String(data: jsonData, encoding: .utf8) ?? ""
// here "decoded" is of type `Any`, decoded from JSON data
return jsonString
// you can now cast it with the right type
} catch {
print(error.localizedDescription)
}
return ""
}
//Convert Swift object to Swift Dictionary
func getDictionary() -> [String: Any] {
var request : [String : Any] = [:]
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let lable = child.label {
//For Nil value found for any swift propery, that property should be skipped. if you wanna print nil on json, disable the below condition
if !checkAnyContainsNil(object: child.value) {
//Check whether is custom swift class
if isCustomType(object: child.value) {
//Checking whether its an array of custom objects
if isArrayType(object: child.value) {
if let objects = child.value as? [AMSwiftBase] {
var decodeObjects : [[String:Any]] = []
for object in objects {
//If its a custom object, nested conversion of swift object to Swift Dictionary
decodeObjects.append(object.getDictionary())
}
request[lable] = decodeObjects
}
}else {
//Not an arry, and custom swift object, convert it to swift Dictionary
request[lable] = (child.value as! AMSwiftBase).getDictionary()
}
}else {
request[lable] = child.value
}
}
}
}
return request
}
//Checking the swift object is swift base type or custom Swift object
private func isCustomType(object : Any) -> Bool {
let typeString = String(describing: type(of: object))
if typeString.contains("String") || typeString.contains("Double") || typeString.contains("Bool") {
return false
}
return true
}
//checking array
private func isArrayType(object : Any) -> Bool {
let typeString = String(describing: type(of: object))
if typeString.contains("Array"){
return true
}
return false
}
//Checking nil object
private func checkAnyContainsNil(object : Any) -> Bool {
let value = "\(object)"
if value == "nil" {
return true
}
return false
}
}
https://github.com/anumothuR/SwifttoJson
This question already has an answer here:
How to Make JSON from Array of Struct in Swift 3?
(1 answer)
Closed 6 years ago.
My model is
public class getCompanyRequestModel
{
public var userLoginId : String?
public var searchString : String?
public var tableName : String?
}
in viewController's viewdidload method, i created object of getCompanyRequestModel
var objGetCompany = getCompanyRequestModel()
objGetCompany.userLoginId = "Dilip";
objGetCompany.searchString = "tata";
objGetCompany.tableName = "null";
now i wanna to get JSON string from objGetCompany same as below
"{\"UserLoginId\":\"Dilip\",\"SearchString\":\"tata\",\"TableName\":\"null\"}";
in C# i get the JSON String from below line of code
string JsonParameters = JsonConvert.SerializeObject(objGetCompany);
Any one interested to solve my issue :-)
Add a property jsonRepresentation to the class:
var jsonRepresentation : String {
let dict = ["userLoginId" : userLoginId, "searchString" : searchString, "tableName" : tableName]
let data = try! JSONSerialization.data(withJSONObject: dict, options: [])
return String(data:data, encoding:.utf8)!
}
By the way: Class names in Swift are supposed to start with a capital letter.
And don't use optionals as a laziness alibi not to write initializers...
Update:
In Swift 4 there is a smarter way: Remove jsonRepresentation and adopt Codable
public class CompanyRequestModel : Codable { ...
then use JSONEncoder
let data = try JSONEncoder().encode(objGetCompany)
let jsonString = String(data: data, encoding: .utf8)!
let text = "{\"UserLoginId\":\"Dilip\",\"SearchString\":\"tata\",\"TableName\":\"null\"}";
if let data = text.data(using: .utf8) {
do {
let dictData = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let company = getCompanyRequestModel()
company.userLoginId = dictData["UserLoginId"] as? String
company.searchString = dictData["SearchString"] as? String
company.tableName = dictData["TableName"] as? String
} catch {
print(error.localizedDescription)
}
}
Considering the following model:
class Person: Object {
dynamic var name = ""
let hobbies = Dictionary<String, String>()
}
I'm trying to stock in Realm an object of type [String:String] that I got from an Alamofire request but can't since hobbies has to to be defined through let according to RealmSwift Documentation since it is a List<T>/Dictionary<T,U> kind of type.
let hobbiesToStore: [String:String]
// populate hobbiestoStore
let person = Person()
person.hobbies = hobbiesToStore
I also tried to redefine init() but always ended up with a fatal error or else.
How can I simply copy or initialize a Dictionary in RealSwift?
Am I missing something trivial here?
Dictionary is not supported as property type in Realm.
You'd need to introduce a new class, whose objects describe each a key-value-pair and to-many relationship to that as seen below:
class Person: Object {
dynamic var name = ""
let hobbies = List<Hobby>()
}
class Hobby: Object {
dynamic var name = ""
dynamic var descriptionText = ""
}
For deserialization, you'd need to map your dictionary structure in your JSON to Hobby objects and assign the key and value to the appropriate property.
I am currently emulating this by exposing an ignored Dictionary property on my model, backed by a private, persisted NSData which encapsulates a JSON representation of the dictionary:
class Model: Object {
private dynamic var dictionaryData: NSData?
var dictionary: [String: String] {
get {
guard let dictionaryData = dictionaryData else {
return [String: String]()
}
do {
let dict = try NSJSONSerialization.JSONObjectWithData(dictionaryData, options: []) as? [String: String]
return dict!
} catch {
return [String: String]()
}
}
set {
do {
let data = try NSJSONSerialization.dataWithJSONObject(newValue, options: [])
dictionaryData = data
} catch {
dictionaryData = nil
}
}
}
override static func ignoredProperties() -> [String] {
return ["dictionary"]
}
}
It might not be the most efficient way but it allows me to keep using Unbox to quickly and easily map the incoming JSON data to my local Realm model.
I would save the dictionary as JSON string in Realm. Then retrive the JSON and convert to dictionary. Use below extensions.
extension String{
func dictionaryValue() -> [String: AnyObject]
{
if let data = self.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject]
return json!
} catch {
print("Error converting to JSON")
}
}
return NSDictionary() as! [String : AnyObject]
} }
and
extension NSDictionary{
func JsonString() -> String
{
do{
let jsonData: Data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String.init(data: jsonData, encoding: .utf8)!
}
catch
{
return "error converting"
}
}
}
UPDATE 2021
Since Realm 10.8.0, it is possible to store a dictionary in a Realm object using the Map type.
Example from the official documentation:
class Dog: Object {
#objc dynamic var name = ""
#objc dynamic var currentCity = ""
// Map of city name -> favorite park in that city
let favoriteParksByCity = Map<String, String>()
}
Perhaps a little inefficient, but works for me (example dictionary from Int->String, analogous for your example):
class DictObj: Object {
var dict : [Int:String] {
get {
if _keys.isEmpty {return [:]} // Empty dict = default; change to other if desired
else {
var ret : [Int:String] = [:];
Array(0..<(_keys.count)).map{ ret[_keys[$0].val] = _values[$0].val };
return ret;
}
}
set {
_keys.removeAll()
_values.removeAll()
_keys.appendContentsOf(newValue.keys.map({ IntObj(value: [$0]) }))
_values.appendContentsOf(newValue.values.map({ StringObj(value: [$0]) }))
}
}
var _keys = List<IntObj>();
var _values = List<StringObj>();
override static func ignoredProperties() -> [String] {
return ["dict"];
}
}
Realm can't store a List of Strings/Ints because these aren't objects, so make "fake objects":
class IntObj: Object {
dynamic var val : Int = 0;
}
class StringObj: Object {
dynamic var val : String = "";
}
Inspired by another answer here on stack overflow for storing arrays similarly (post is eluding me currently)...