如何为以下 JSON 数据创建模型类并解析它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38612198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create the model class for the following JSON data and parse it?
提问by PRADIP KUMAR
My JSON data
我的 JSON 数据
{
"addon_items" : [
{
"aname" : "",
"id" : "2588",
"name" : "Plain Nan",
"order" : "1",
"aid" : "259",
"Sub_Add_Items" : "",
"icon" : "",
"status" : "1",
"next" : "0",
"price" : "0.60"
},
{
"aname" : "",
"id" : "2589",
"name" : "Pitta Bread",
"order" : "2",
"aid" : "259",
"Sub_Add_Items" : "",
"icon" : "",
"status" : "1",
"next" : "0",
"price" : "0.00"
}
],
"addon" : {
"description" : "Please choose your Nan bread",
"aname" : "",
"id" : "259",
"icon" : "",
"limit" : "1",
"special_addon" : "",
"next" : "165"
}
}
I created three class models named AddOnResponse, AddOn, AddOnItems like this:
我创建了三个名为 AddOnResponse、AddOn、AddOnItems 的类模型,如下所示:
AddOnResponse class model
AddOnResponse 类模型
class AddOnResponse {
var addon: Array<String>?
var addonitems: Array<AnyObject>?
init(addon:Array<String>?,addonitems: Array<AnyObject>?){
self.addon = addon
self.addonitems = addonitems
}
}
AddOn class model
附加类模型
class AddOn {
var id: Int?
var icon: String?
var desc: String?
var limit: Int?
var next: Int?
var aname: String?
var specialaddon: Int?
init(id: Int?,icon: String?,desc: String?,limit: Int?,next: Int?,aname: String?,specialaddon: Int?){
self.id = id
self.icon = icon
self.desc = desc
self.limit = limit
self.next = next
self.aname = aname
self.specialaddon = specialaddon
}
}
AddOnItems class model
AddOnItems 类模型
class AddOnItems {
var id: Int?
var aid: Int?
var name: String?
var price: Int?
var order: Int?
var status: Int?
var next: Int?
var aname: String?
var subaddItems: Int?
var icon: String?
init(id: Int?,aid: Int?,name: String?,price: Int?,order: Int?,status: Int?,next: Int?,aname: String?,subaddItems: Int?,icon: String?){
self.id = id
self.aid = aid
self.name = name
self.price = price
self.order = order
self.status = status
self.next = next
self.aname = aname
self.subaddItems = subaddItems
self.icon = icon
}
}
Now I am fetching my JSON data using Alamofire but when accepting dat into class model using object I am getting nil value.
现在我正在使用 Alamofire 获取我的 JSON 数据,但是当使用 object 将 dat 接受到类模型时,我得到了 nil 值。
var addonResponses = [AddOnResponse]()
Alamofire.request(.GET, myAddOnUrl)
.validate()
.responseJSON
{ response in
switch response.result
{
case .Success:
if let value = response.result.value{
let json = JSON(value)
print(json)
print(json["addon"].arrayValue)
for(_,content) in json{
let addOnRes = AddOnResponse(addon:content["addon"].arrayValue,
addonitems:content["addon_items"].Arrayobject)
print(self.addonResponses.count)
print(addOnRes.addon)
print(addOnRes.addonitems)
}
}
The addon and addonitems data are coming nil, why?
addon 和 addonitems 数据都为零了,为什么?
回答by nishantdesai
After going through your JSON response, what I see is that you are getting an object which has two nodes(or properties). First- "addon_items" which has as array and for which you have created a class AddOnItems which is correct. Second- "addon": this key over here is reference to a 'Dictionary' rather than to an array.
在查看您的 JSON 响应后,我看到您正在获取一个具有两个节点(或属性)的对象。首先-“addon_items”,它具有数组,并且您已经为其创建了一个正确的类 AddOnItems。第二个“插件”:这里的这个键是对“字典”的引用,而不是对数组的引用。
So to store the response in your AddOnResponse object, try the following code.
因此,要将响应存储在您的 AddOnResponse 对象中,请尝试以下代码。
Alamofire.request(.GET, myAddOnUrl).validate().reponseJSON { response in
switch resonse.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
let responseDictionary = json.dictionaryValue as? [String: AnyObject]
let addOnRes = AddOnResponse(addon:responseDictionary["addon"].dictionaryValue, addonitems:responseDictionary["addon_items"].arrayValue)
}
case .Failure:
break
}
}
Also make change to your AddOnResponse class
还要更改您的 AddOnResponse 类
class AddOnResponse {
var addon: [String: AnyObject]?
var addonitems: Array<AnyObject>?
init(addon:[String: AnyObject]?,addonitems: Array<AnyObject>?){
self.addon = addon
self.addonitems = addonitems
}
}
TL;DRYour JSON response doesn't properly correspond to the model you've made in your app. Double check the "addon" key of your json response which has a dictionary object to it and NOT AN ARRAY and accordingly make your model classes.
TL;DR您的 JSON 响应与您在应用程序中创建的模型不正确对应。仔细检查您的 json 响应的“addon”键,该键有一个字典对象,而不是数组,并相应地制作您的模型类。
Edit: Rectifying the mistake to point the casting error. What I would now suggest is that pass the JSON object for `add_on' key. In the AddOn class change the initialiser so that it takes a JSON object. Then initialising them using. AddOn Class Initialiser
编辑:纠正错误以指出铸造错误。我现在建议的是为`add_on' 键传递 JSON 对象。在 AddOn 类中更改初始化程序,使其采用 JSON 对象。然后使用初始化它们。 附加类初始化器
init(json: JSON) {
id = json["id"].intValue
name = json["name"].stringValue
// and so on
}
Similarly do the same for AddOnItems. And in the AddOnResponse initialiser iterate in a loop the JSON object for AddOnItems. Initialise it and append to the addOnItems array property. Sorry cannot write the code for it right now. Got a time constraint.
同样对 AddOnItems 做同样的事情。并在 AddOnResponse 初始化程序中循环迭代 AddOnItems 的 JSON 对象。初始化它并附加到 addOnItems 数组属性。抱歉,现在无法为它编写代码。有时间限制。
回答by Ved Rauniyar
import Foundation
import SwiftyJSON
class UserInfo {
var mobile : Int?
var userid : Int?
var email : String?
var name : String?
init() {
}
init(json : JSON){
mobile = json["phone_number"].intValue
userid = json["id"].intValue
email = json["email"].stringValue
name = json["name"].stringValue
}
}
回答by Prashant Ghimire
Try this. I have done this using AlamofireObjectMapper. Check AlamofireObjectMapperfor more info
尝试这个。我已经使用AlamofireObjectMapper. 查看AlamofireObjectMapper更多信息
import UIKit
import ObjectMapper
class FollowList: Mappable {
var addonItems : [addonItemsList]?
required init?(_ map: Map) {
super.init(map)
}
override func mapping(map: Map) {
super.mapping(map)
addonItems <- map["addon_items"]
}
}
class addonItemsList : Mappable{
var aname : String?
var id : String?
var name : String?
var order : Int?
var aname : Int?
required init?(_ map: Map) {
}
func mapping(map: Map) {
aname <- map["aname"]
id <- map["id"]
order <- map["order"]
name <- map["name"]
icon <- map["icon"]
}
}
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"
Alamofire.request(.GET, URL)..responseArray { (response: Response<[FollowList], NSError>) in { (response: Response< FollowList, NSError>) in
expectation.fulfill()
let FollowList = response.result.value
print(FollowList?. addonItems)
}
回答by PRADIP KUMAR
After so many experiments I got the answer. I have to pass the data to objects like this way. i followed @nishantdesai answers and do some modifications..
经过如此多的实验,我得到了答案。我必须以这种方式将数据传递给对象。我按照@nishantdesai 的回答进行了一些修改。
Alamofire.request(.GET, myAddOnUrl)
.validate()
.responseJSON
{ response in
switch response.result
{
case .Success:
if let value = response.result.value{
let json = JSON(value)
let addOnRes = AddOnResponse(addon: json["addon"].object as? [String : AnyObject],
addonitems: json["addon_items"].arrayObject)
print(addOnRes.addon)
print(addOnRes.addonitems)
}
回答by Arshad Shaik
Its very simple to create model class, please follow the below procedure.
创建模型类非常简单,请按照以下步骤操作。
Create swift class with name "Sample", write the code as below.
创建名为“Sample”的 swift 类,编写如下代码。
Class Sample{
var id:String?
var aname:String?
var name:String?
var order:String?
var aid:String?
var Sub_Add_Items:String?
var icon:String?
var status:String?
var next:String?
var price:String?
func update(info: JSON) {
id = data["id"].string
aname = data["aname"].string
name = data["name"].string
order = data["order"].string
aid = data["aid"].string
Sub_Add_Items = data["Sub_Add_Items"].string
icon = data["icon"].string
status = data["status"].string
next = data["next"].string
price = data["price"].string
}
}
and also create one more swift class as "Details" code as below,
并创建另一个 swift 类作为“详细信息”代码,如下所示,
Class Details{
var list: [Sample] = [Sample]()
func addDetails(data: JSON){
for(_, detailObj) in data {
let sampleObj = Sample()
sampleObj.update(detailObj)
list.append(sampleObj)
}
}
}
and in your viewcontroller before viewdidload()method create an object of Details class as
并在viewdidload()方法之前的视图控制器中创建一个 Details 类的对象作为
var detailsObj = Details()
After you got the response from alamofire request method, call the method as below:
从 alamofire 请求方法得到响应后,调用如下方法:
self.detailsObj.addDetails(data!["addon_items"] as JSON)
Data is nothing but the response that you get from alamofire.
数据只不过是您从 alamofire 获得的响应。
Later you can access the variables as below:
稍后您可以访问变量,如下所示:
detailsObj.list[0].name
and you can display it.
你可以显示它。
回答by ajaykoppisetty
You can use ObjectMapper
您可以使用ObjectMapper
class AddOn: Mappable {
var description: String!
var aname: String?
var id: String!
var icon: String?
var limit: String?
var special_addon: String?
var next: String?
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
description <- map["description"]
aname <- map["aname"]
id <- map["id"]
icon <- map["icon"]
limit <- map["limit"]
special_addon <- map["special_addon"]
next <- map["next"]
}
}
class AddOnItems: Mappable {
var aname: String?
var id:String!
var name: String!
var order: String?
var Sub_Add_Items: String?
var status: String!
var next: String!
var price: String!
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
aname <- map["aname"]
id <- map["id"]
name <- map["name"]
order <- map["order"]
Sub_Add_Items <- map["Sub_Add_Items"]
status <- map["status"]
next <- map["next"]
price <- map["price"]
}
}
class requirement: Mappable {
var addOnItems: [AddOnItems]?
var addOn: AddOn!
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
addOnItems <- map["addon_items"]
addOn <- map["addon_items"]
}
}

