Commit 6305b4d2 authored by 陈业泓's avatar 陈业泓

update

parent 79b722d6
File added
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
uuid = "0DEDF84D-949E-48C0-A56B-73E77D9298BD"
type = "1"
version = "2.0">
</Bucket>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>MacJsonToModelFile.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>
//
// AppDelegate.swift
// MacJsonToModelFile
//
// Created by chenyehong on 2022/2/21.
//
import Cocoa
@main
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
}
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"images" : [
{
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
This diff is collapsed.
//
// FileModel.swift
// MacJsonToModelFile
//
// Created by chenyehong on 2022/2/21.
//
import Cocoa
class FileModel: NSObject {
var fileName : String?
var propertys : [FileProperty] = []
}
class FileProperty : NSObject {
var propertyName : String?
var propertyType : PropertyType?
}
enum PropertyType{
case id
case int
case string
case float
case bool
case model(String)
case list(ArrayItemType)
}
enum ArrayItemType{
case id
case int
case string
case float
case bool
case model(String)
}
//
// FileUtil.swift
// MacJsonToModelFile
//
// Created by chenyehong on 2022/2/21.
//
import Cocoa
class FileUtil: NSObject {
let manager = FileManager.default
func clearFile(){
let exist = manager.fileExists(atPath: fileDir.path)
if exist {
do {
try manager.removeItem(atPath: fileDir.path)
print("已存在,删除成功")
} catch {
print("已存在,删除失败")
}
}
do {
try manager.createDirectory(at: fileDir, withIntermediateDirectories: true, attributes: nil)
print("创建文件夹成功")
} catch {
print("创建文件夹失败")
}
}
func createOcFile(_ model : FileModel){
let header = ObjcUtil.headerTextByModel(model)
createFile("\(model.fileName!).h", header)
let implement = ObjcUtil.implementByModel(model)
createFile("\(model.fileName!).m", implement)
}
func createFile(_ fileName : String, _ content : String){
let file = fileDir.appendingPathComponent(fileName)
print("文件: \(file)")
let exist = manager.fileExists(atPath: file.path)
if !exist {
let createSuccess = manager.createFile(atPath: file.path,contents:content.data(using: String.Encoding.utf8),attributes:nil)
print("文件创建结果: \(createSuccess)")
}
}
lazy var fileDir : URL = {
let manager = FileManager.default
let urlForDocument = manager.urls( for: .desktopDirectory,
in:.userDomainMask)
let url = urlForDocument[0].appendingPathComponent("__ModelResult", isDirectory: true)
return url
}()
func test(){
//在桌面上创建一个文件
let manager = FileManager.default
let urlForDocument = manager.urls( for: .desktopDirectory,
in:.userDomainMask)
let url = urlForDocument[0]
createFile(name:"test.txt", fileBaseUrl: url)
}
//根据文件名和路径创建文件
func createFile(name:String, fileBaseUrl:URL){
let manager = FileManager.default
let file = fileBaseUrl.appendingPathComponent(name)
print("文件: \(file)")
let exist = manager.fileExists(atPath: file.path)
if !exist {
//在文件中随便写入一些内容
let str = "hello json"
let createSuccess = manager.createFile(atPath: file.path,contents:str.data(using: String.Encoding.utf8),attributes:nil)
print("文件创建结果: \(createSuccess)")
} else {//删除操作
do {
try manager.removeItem(atPath: file.path)
} catch {
}
}
}
}
//
// ObjcUtil.swift
// MacJsonToModelFile
//
// Created by chenyehong on 2022/2/21.
//
import Cocoa
class ObjcUtil: NSObject {
static func headerTextByModel(_ model : FileModel) -> String{
var includeList : [String] = []
var content = ""
for pt in model.propertys {
let propertyName = replacedPropertyName(pt.propertyName!)
switch pt.propertyType {
case .id:
content += "@property (strong, nonatomic) id \(propertyName);\n"
case .int:
content += "@property (assign, nonatomic) NSInteger \(propertyName);\n"
case .string:
content += "@property (copy, nonatomic) NSString *\(propertyName);\n"
case .float:
content += "@property (assign, nonatomic) double \(propertyName);\n"
case .bool:
content += "@property (assign, nonatomic) BOOL \(propertyName);\n"
case .model(let pName):
content += "@property (strong, nonatomic) \(pName) *\(propertyName);\n"
if !includeList.contains(pName){
includeList.append(pName)
}
break
case .list(let itemType):
switch itemType {
case .string:
content += "@property (copy, nonatomic) NSArray <NSString*> *\(propertyName);\n"
case .model(let pName):
content += "@property (copy, nonatomic) NSArray <\(pName)*> *\(propertyName);\n"
if !includeList.contains(pName){
includeList.append(pName)
}
default:
content += "@property (copy, nonatomic) NSArray *\(propertyName);\n"
}
break
default:
break
}
}
var includeTxt = getIncludeTxt(model.fileName!)
includeTxt += "#import <Foundation/Foundation.h>\n"
for item in includeList {
includeTxt += "#import \"\(item).h\"\n"
}
includeTxt += "\n@interface \(model.fileName!) : NSObject\n\n"
content = includeTxt + content
content = content + "\n@end"
return content
}
static func implementByModel(_ model : FileModel) -> String{
var content = getIncludeTxt(model.fileName!)
content += "#import \"\(model.fileName!).h\"\n\n"
content += "@implementation \(model.fileName!)\n\n"
var replaceCode = ""
for pt in model.propertys {
let propertyName = replacedPropertyName(pt.propertyName!)
if propertyName != pt.propertyName! {
replaceCode += " @\"\(propertyName)\" : @\"\(pt.propertyName!)\",\n"
}
}
if replaceCode.count > 0 {
replaceCode =
"+ (NSDictionary *)mj_replacedKeyFromPropertyName {\n" +
" return @{\n" +
replaceCode +
" };\n" +
"}\n\n"
content += replaceCode
}
var classInArrayCode = ""
for pt in model.propertys {
switch pt.propertyType {
case .list(let itemType):
switch itemType {
case .model(let pName):
classInArrayCode += " @\"\(pt.propertyName!)\" : NSStringFromClass(\(pName).class),\n"
break
default:
break
}
default:
break
}
}
if classInArrayCode.count > 0 {
classInArrayCode =
"+ (NSDictionary *)mj_objectClassInArray {\n" +
" return @{\n" +
classInArrayCode +
" };\n" +
"}\n\n"
content += classInArrayCode
}
content += "@end"
return content
}
static func getIncludeTxt(_ fileName : String) -> String {
return "//\n" +
"// \(fileName).h\n" +
"// MacJsonToModelFile\n" +
"//\n" +
"// Created by mac on 2022/xx/xx.\n" +
"// Copyright © 2022 mac. All rights reserved.\n" +
"//\n\n"
}
static func replacedPropertyName(_ key : String) -> String {
if let name = replacedDic[key] {
return name
}
return key
}
static let replacedDic = ["id":"ID"]
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict/>
</plist>
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "OcTool.h"
//
// OcTool.h
// MacJsonToModelFile
//
// Created by chenyehong on 2022/2/22.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface OcTool : NSObject
+ (BOOL)isPureFloat: (id)obj;
+ (BOOL)isPureBool: (id)obj;
+ (BOOL)isPureInt: (id)obj;
@end
NS_ASSUME_NONNULL_END
//
// OcTool.m
// MacJsonToModelFile
//
// Created by chenyehong on 2022/2/22.
//
#import "OcTool.h"
@implementation OcTool
+ (BOOL)isPureFloat: (id)obj{
if ([obj isKindOfClass:[NSNumber class]]) {
if (strcmp([obj objCType], @encode(float)) == 0 ||
strcmp([obj objCType], @encode(CGFloat)) == 0) {
return YES;
}
}
return NO;
}
+ (BOOL)isPureBool: (id)obj{
if ([obj isKindOfClass:[NSNumber class]]) {
if (strcmp([obj objCType], @encode(BOOL)) == 0) {
return YES;
}
}
return NO;
}
+ (BOOL)isPureInt: (id)obj{
NSScanner *scan = [NSScanner scannerWithString:[NSString stringWithFormat:@"%@", obj]];
int val;
return [scan scanInt:&val] && [scan isAtEnd];
}
@end
//
// ViewController.swift
// MacJsonToModelFile
//
// Created by chenyehong on 2022/2/21.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBOutlet weak var myScrollView: NSScrollView!
let fileUtil = FileUtil.init()
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func clickStart(_ sender: Any) {
let myTextView: NSTextView = myScrollView.documentView! as! NSTextView
let myText:String = myTextView.string
let data = myText.data(using: String.Encoding.utf8)
if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] {
print("转换成功")
fileMap = [:]
fileUtil.clearFile()
handleDic("Result", dict as NSDictionary)
for (key, value) in fileMap {
fileUtil.createOcFile(value)
}
// return dict
} else {
print("请输入正确的json字符串")
}
}
var prefix = "SLM"
var fileMap : [String : FileModel] = [:]
func handleDic(_ name : String, _ dic : NSDictionary) -> String {
var fileName = "\(prefix)\(name.capitalized)"
var count = 0
while fileMap.contains(where: { (key: String, value: FileModel) in
return key == fileName
}) {
count += 1
fileName = "\(prefix)\(count)\(name.capitalized)"
}
let fileModel = FileModel.init()
fileModel.fileName = fileName
fileMap[fileModel.fileName!] = fileModel
for (key, value) in dic {
let pt = FileProperty.init()
pt.propertyName = key as! String
pt.propertyType = calPropertyType(pt.propertyName!, value)
fileModel.propertys.append(pt)
}
return fileName
}
func calPropertyType(_ name : String, _ value : Any) -> PropertyType{
if let value = value as? NSDictionary {
let pName = handleDic(name, value)
return PropertyType.model(pName)
}
if let array = value as? NSArray {
if array.count > 0 {
let obj = array[0]
if let obj = obj as? NSDictionary {
let pName = handleDic(name, obj)
return PropertyType.list(ArrayItemType.model(pName))
}
if obj is String {
return PropertyType.list(.string)
}
if OcTool.isPureFloat(value) {
return PropertyType.list(.float)
}
if OcTool.isPureBool(value) {
return PropertyType.list(.bool)
}
if OcTool.isPureInt(value) {
return PropertyType.list(.int)
}
}
return PropertyType.list(.id)
}
if value is String {
return .string
}
if OcTool.isPureFloat(value) {
return .float
}
if OcTool.isPureBool(value) {
return .bool
}
if OcTool.isPureInt(value) {
return .int
}
return .id
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment