100
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftAdvent Calendar 2014

Day 7

JSONExportを使ってjsonからswiftのクラスを自動生成

Posted at

モデルをたくさん作るのが面倒、そんなときに、jsonからmodelが生成できたら便利じゃないですか?
JSONExportを使うとjsonから自動でmodelが生成できます。
swiftだけでなく、objective Cやandroid用のモデルもできます。

スクリーンショット 2014-12-07 21.13.26.png

実際どういうことができるか

  • 例えばこのようなjsonがあれば、以下のmodelを自動で生成できます。
  • Rootクラス名がをProject、Class PrefixをWTDとする。
{
  "projectID": 12,
  "title": "ガチエンジニアウォンテッド",
  "location": "東京",
  "company": {
    "companyID": 100,
    "name": "Wantedly"
  }
}
import Foundation

class WTDProject{

	var company : WTDCompany!
	var location : String!
	var projectID : Int!
	var title : String!


	/**
	 * Instantiate the instance using the passed dictionary values to set the properties values
	 */
	init(fromDictionary dictionary: NSDictionary){
		if let companyData = dictionary["company"] as? NSDictionary{
			company = WTDCompany(fromDictionary: companyData)
		}
		location = dictionary["location"] as? String
		projectID = (dictionary["projectID"] as? NSString)?.intValue
		title = dictionary["title"] as? String
	}

	/**
	 * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
	 */
	func toDictionary() -> NSDictionary
	{
		var dictionary = NSMutableDictionary()
		if company != nil{
			dictionary["company"] = company.toDictionary()
		}
		if location != nil{
			dictionary["location"] = location
		}
		if projectID != nil{
			dictionary["projectID"] = projectID
		}
		if title != nil{
			dictionary["title"] = title
		}
		return dictionary
	}

}
import Foundation

class WTDCompany{

	var companyID : Int!
	var name : String!


	/**
	 * Instantiate the instance using the passed dictionary values to set the properties values
	 */
	init(fromDictionary dictionary: NSDictionary){
		companyID = (dictionary["companyID"] as? NSString)?.intValue
		name = dictionary["name"] as? String
	}

	/**
	 * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
	 */
	func toDictionary() -> NSDictionary
	{
		var dictionary = NSMutableDictionary()
		if companyID != nil{
			dictionary["companyID"] = companyID
		}
		if name != nil{
			dictionary["name"] = name
		}
		return dictionary
	}

}

手順

変換できる種類

  • Swift - Class(上の例)
  • Swift - CoreData
  • Swift - Realm
  • Swift - Struct
  • SwiftyJSON - Class
  • Java for Android
  • Objective C - iOS
  • Objective C - Mac
  • Objective C - CoreData
  • Objective C - Realm
    • Realmというのは、データ量が多い時にsqlLiteよりもパフォーマンスのよいデータベース。
    • 無料で、今年7月にHackerNewsで話題なっていて、Zyngaは2012年から使っているらしい。
    • http://qiita.com/moriyaman/items/1a2916f4c2b79e934370

[One more thing] JSONExportを自分なりに拡張する

  • JSONExportはswiftで描かれている
  • デフォルトでもUnility Methodというオプションがある。これにチェックして出力すると、toDictionaryというメソッドが追加される
  • JSONでそれぞれの時にどのように出力するか決まっている
  • Supported LanguagesというディレクトリにSwift-Class.jsonあるり、その中のutilityMethodsに必要なメソッドを追加することができる。
  • forEachPropertyが通常のプロパティで、forEachCustomTypePropertyがカスタムクラスのプロパティで、forEachArrayOfCustomTypePropertyがArrayのプロパティ。それぞれどう出力したいか書けるようになっている。

    "utilityMethods": [
                       {
                       "comment": "\t/**\n\t * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property\n\t */\n",
                       "signature": "\tfunc toDictionary() -> NSDictionary",
                       "bodyStart": "\n\t{\n",
                       "bodyEnd": "\t}\n",
                       "body": "\t\tvar dictionary = NSMutableDictionary()\n",
                       "forEachProperty": "\t\tif <!VarName!> != nil{\n\t\t\tdictionary[\"<!JsonKeyName!>\"] = <!VarName!>\n\t\t}\n",
                       "forEachCustomTypeProperty" : "\t\tif <!VarName!> != nil{\n\t\t\tdictionary[\"<!JsonKeyName!>\"] = <!VarName!>.toDictionary()\n\t\t}\n",
                       "forEachArrayOfCustomTypeProperty": "\t\tif <!VarName!> != nil{\n\t\t\tvar dictionaryElements = [NSDictionary]()\n\t\t\tfor <!VarName!>Element in <!VarName!> {\n\t\t\t\tdictionaryElements.append(<!VarName!>Element.toDictionary())\n\t\t\t}\n\t\t\tdictionary[\"<!JsonKeyName!>\"] = dictionaryElements\n\t\t}\n",
                       "returnStatement": "\t\treturn dictionary\n"
                       }
                       ]

	/**
	 * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
	 */
	func toDictionary() -> NSDictionary
	{
		var dictionary = NSMutableDictionary()
		if companyID != nil{
			dictionary["companyID"] = companyID
		}
		if name != nil{
			dictionary["name"] = name
		}
		return dictionary
	}
100
98
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
100
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?