Creating Model using Swifty JSon Model - json

[
{
"_id": "1212323",
"row": 1,
"column": 1,
"displayType": 0,
"item": {
"type": "category_",
"data": {
"_id": "595a1446cb91951900b0b4b0",
"title": "something",
"fullImage": "http://assets.something.mobi/curated/something (2).jpg",
"halfImage": "http://assets.something.mobi/curated/something (1).jpg"
}
}
},
{
"_id": "595a148ccb91951900b0b4b5",
"row": 2,
"column": 1,
"displayType": 1,
"item": {
"type": "curatedlist",
"data": {
"_id": "595b34abcb9195190c0ae378",
"active": "true",
"title": "sample something list",
"fullImage": "http://assets.something.mobi/curated/something (2).jpg",
"halfImage": "http://assets.something.mobi/curated/something (2).jpg"
}
}
}
]
very new to SwiftyJSON and Alamofire some one please help me to create a model for it im able get JSON responce using almofire but not able to create a proper swifty json model for this

I have done this using two separate model classes, one to directly map all the values and other used to fetch directly as an array from it.
For some who just starting or stuck with creating model and mapping values can try these or someone is an expert can suggest a better solution to improve the implementation
1.CategoryModel: NSObject
import UIKit
import SwiftyJSON
class CategoryModel: NSObject {
var resultArray : NSArray!
var _id : String!
var row : NSInteger!
var column : NSInteger!
var displayType : NSInteger!
var type : String?
var _id1 : String?
var title : String?
var fullImage : String?
var halfImage : String?
// var item
required init(JsonDashBoard: JSON) {
_id = JsonDashBoard["_id"].stringValue
row = JsonDashBoard["row"].intValue
column = JsonDashBoard["column"].intValue
displayType = JsonDashBoard["displayType"].intValue
//MARK:- Inside Item Dictionary
type = JsonDashBoard["item"]["type"].stringValue
//MARK:- Inside Item/dataDictionary
_id1 = JsonDashBoard["item"]["data"]["_id"].stringValue
title = JsonDashBoard["item"]["data"]["title"].stringValue
fullImage = JsonDashBoard["item"]["data"]["fullWidthImage"].stringValue
halfImage = JsonDashBoard["item"]["data"]["halfWidthImage"].stringValue
}
}
2.CategoryListModel:NSObject
import UIKit
class CategoryListModel: NSObject {
var items : NSArray? = nil;
required init(_items: NSMutableArray) {
self.items = _items
}
}
and using these model classes you can map values using the below code snipet
manager.request(routeUrl, method: .get).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
let resJson = JSON(responseObject.result.value!)
let categoryList = NSMutableArray()
for (_,subJson):(String, JSON) in resJson {
let model = CategoryModel(JsonDashBoard: subJson)
categoryList.add(model)
//Do something you want
print(subJson)
}
let categoryListModel = CategoryListModel(_items: categoryList)
success(categoryListModel)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
failure(error)
}
}

Related

Error message : Expected BEGIN_ARRAY but was BEGIN_OBJECT from my own rest server Localhost

I'm trying to get JSON on android from my own rest server on localhost using okHttp like this:
JSON
{
"status": true,
"data": [
{
"id": "1",
"title": "Jadwal Catin 2021",
"description": "bismillah"
},
{
"id": "2",
"title": "Jadwal Vaksin Covid Lansia",
"description": "Tanggal 16-Juli-2021 di puskesmas perwira sudah bisa vaksin covi-19 untuk lansia"
}
]
}
Data Class
class Placeholder {
var userId: Int? = null
var id: Int? = null
var title: String? = null
#SerializedName("description")
var body: String? = null
}
Into Recycleview
override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
val body = response.body!!.string()
var gson = GsonBuilder().create()
var result = gson.fromJson(body, Array<Placeholder>::class.java).toList()
runOnUiThread {
beritaAdapter.setData(result)
}
Any ideas how should I fix it?
The JSON you show here is not just an array of Placeholder, it's a JSON object ({ ... }), which itself contains 2 properties status and data. And data is an array of objects that partially match your Placeholder class.
You can represent the overall JSON by the following class:
class PlaceholdersResponse {
var status: Boolean
var data: List<Placeholder>
}
And you can access your data array this way:
var result = gson.fromJson(body, PlaceholdersResponse::class.java).data.toList()

Parsing JSON in Swift without array key

I have a JSON-response:
[
[{
"id": "1",
"name": "Toyota",
"model": "Camry"
},
{
"id": "2",
"name": "Nissan",
"model": "Almera"
}
],
{
"count": "1234",
"page": "1"
}
]
I create decodable model:
struct Car: Decodable {
var id: String?
var name: String?
var model: String?
}
I'm trying extract data like this, for test:
let carsResponse = try JSONDecoder().decode([[Car]].self, from: data)
print(carsResponse[0])
And I have an error:
Expected to decode Array but found a dictionary instead.
What is wrong?
This format is pretty bad, so you'll need to decode the outer container by hand, but it's not difficult:
struct CarResponse: Decodable {
var cars: [Car]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
cars = try container.decode([Car].self) // Decode just first element
}
}
let carsResponse = try JSONDecoder().decode(CarResponse.self, from: data)
print(carsResponse.cars)

How to create a Swift model for JSON

{"dataList":{"1547795650562": {
"c0a8007b-6759-111d-8167-59e8dabe0086": {
"recordDate": 1547795650562,
"resultValue": "160",
"vitalParameter": {
"uom": {
"code": "KG",
"name": "KG",
"id": "c0a8007b-6759-111d-8167-59e76204007f"
},
"resultType": {
"code": "VSRTNUMERIC",
"name": "Numeric",
"id": "20cf4756-40b0-4cc1-acb5-861765370a41"
},
"code": "29463-7",
"name": "Weight",
"id": "c0a8007b-6759-111d-8167-59e8dabe0086"
},
"id": "c0a8007b-6855-1d16-8168-5fd18fa301b7"
}}
}}
getting 1547795650562 and c0a8007b-6759-111d-8167-59e8dabe0086 as class names. But I dont want like this;
class DataList : NSObject, NSCoding{
var 1547795650562 : 1547795650562!
}
class 1547795650562 : NSObject, NSCoding{
var c0a8007b6759111d816759e8dabe0086 : VitalParameter!
}
But the problem here is, 1547795650562 and c0a8007b-6759-111d-8167-59e8dabe0086 cannot be hard coded because they may change.
c0a8007b-6759-111d-8167-59e8dabe0086 is dynamic id and 1547795650562 is recordDate. Inner object is repetitive.
But I have to map as the keys are of recordDate and id respectively.
Try using Codable instead of NSCoding to parse your JSON data.
Models:
struct Root: Codable {
let dataList: [String:[String:Record]]
}
struct Record: Codable {
let recordDate: Int
let resultValue: String
let vitalParameter: VitalParameter
let id: String
}
struct VitalParameter: Codable {
let uom, resultType: ResultType
let code, name, id: String
}
struct ResultType: Codable {
let code, name, id: String
}
Parse the JSON data using above models like,
do {
let response = try JSONDecoder().decode(Root.self, from: data)
print(response)
} catch {
print(error)
}
Note: You can use https://app.quicktype.io to get the models from your JSON instantly. Make the changes as per your requirement and you're good to go.

Using SwiftyJSON for subarray with Swift 3.1

I have a json data. I never use SwiftyJSON before. I am trying first time.
My json like this:
[
{
"Id": 1,
"Name": "A",
"SubNames": [
{
"SubId": 1,
"SubName": "A1"
},
{
"SubId": 2,
"SubName": "A2"
}]
},
{
"Id": 2,
"Name": "B",
"SubNames": [
{
"SubId": 1,
"SubName": "B1"
},
{
"SubId": 2,
"SubName": "B2"
}]
}
]
I can handle Name and append a array. But I can't handle SubNames. I tried somethings but doesn't work unfortunately. I want to append SubNames a array. This array will be like this:
[["A1","A2"],["B1","B2"]]
I use this code:
let json = JSON(data: data!)
for (_,subJson):(String, JSON) in json {
self.names.append(subJson["Name"].stringValue
}
try this to access those fields, and you shouldn't do data! here
guard let `data` = data else {
//no data handling
return
}
let dataArray = JSON(data: data).arrayValue
var arrayOfAllSubnames: [[String]] = [[]]
for object in dataArray {
var arrayOfSubnames: [String] = []
if let subnames = object["SubNames"].array {
for subname in subnames {
//here you get `"SubId": 2, "SubName": "B2"` object
let subnameValue = subname["SubName"].stringValue
arrayOfSubnames.append(subnameValue)
}
}
arrayOfAllSubnames.append(arrayOfSubnames)
}
Swift 3.0
1) First declare sub name array.
var subNameArray: [[String]] = []
2) you can access and store this objects as below.
let json = JSON(data: data!).arrayValue
for item in json {
var tempArray: [String] = []
let name = item["Name"].stringValue
for subNameItem in items["SubNames"].arrayValue {
tempArray.append(subNameItem["SubName"].stringValue)
}
subNameArray.append(tempArray)
}

Get JSON element swift

I am working receiving the following JSON file in Swift and I cant figure out how get the details elements in the JSON
[
{
"id": 143369,
"history": "jd2",
"details": [
{
"name": "Su 1",
"color": "#ffffff"
},
{
"name": "Stu 1",
"color": "#ffffff"
}
]
},
{
"id": 143369,
"history": "musa 2",
"details": [
{
"name": "Stu 1",
"color": "#ffffff"
},
{
"name": "Stu 2",
"color": "#ffffff"
}
]
}
]
I have created this class with which I am able to retrieve id and history but not the details. How do I include the details with the id and history?
public class students {
let id: Int32
let history: String?
init(id:Int32, history:String) {
self.id = id
self.history = name
}
}
Below is my web service code.
var dataArray = [students]()
Alamofire.request(.GET, url)
.responseJSON { response in
if let value: AnyObject = response.result.value {
let json = JSON(value)
if let items = json.array {
for item in items {
self.dataArray.append(students(
id: item["id"].int32!,
history: item["history"].string!))
let cItems = item["details"].array
for citem in citems {
//here
}
}
}
}
}
your student model should be like this.
let id: Int32
let history: String?
let details: Array<[String:AnyObject]>
init(id:Int32, history:String,details:Array<[String:AnyObject]>) {
self.id = id
self.history = name
self.details= details //need a cast here!
}
here is a simple parser for i used for a project to cast your Array<[String:AnyObject]> as you
func collection(data:[[String:AnyObject]]) -> [yourModel] {
var objectArray: [yourModel] = []
for d in data {
let obj = yourModel(data: d as [String: AnyObject]) // i created a initializer for this object here on my project.
objectArray.append(obj)
}
return objectArray
}
hope gives an idea!