Skip to content

Instantly share code, notes, and snippets.

@tonycn
Created April 12, 2014 06:48
Show Gist options
  • Save tonycn/10522057 to your computer and use it in GitHub Desktop.
Save tonycn/10522057 to your computer and use it in GitHub Desktop.
sublime plugin to generate ObjC property code
# -*- coding: utf-8 -*-
import sublime, sublime_plugin
import json
class JsonpropCommand(sublime_plugin.TextCommand):
"""
Test 1:
{"a" : "abc", "b" : 1}
Test 2:
{"a" : "abc", "b" : 1, "c" : [1, 2, 3]}
Test 3:
{"a" : "abc", "b" : 1, "c" : [1, 2, 3], "d" : {"d1" : 1, "d2" : "2"}}
Test 4:
{"a" : "abc", "b" : 1, "c" : [{"c1" : 1, "c2" : "2"}], "d" : {"d1" : 1, "d2" : "2"}}
"""
def run(self, edit):
for region in self.view.sel():
self.generate_model_from_region(edit, region)
def generate_model_from_region(self, edit, region):
region_str = self.view.substr(region)
# print(region_str)
try:
jsonobject = json.loads(region_str)
except Exception:
return
print("jsonobject origin", jsonobject, type(jsonobject))
if jsonobject is not None and type(jsonobject) is dict:
self.generate_objc_properties(edit, jsonobject, 'root')
pass
pass
def generate_objc_properties(self, edit, jsonobject, obj_name):
# print("generate_objc_properties jsonobject:", jsonobject)
if jsonobject is None or type(jsonobject) is not dict:
return
perperties = '';
for key, value in jsonobject.items():
# print("generate_objc_properties key and value:", key, value)
if type(value) is str:
perperties += "@property (nonatomic, strong) NSString *%s;\n" % key
pass
elif type(value) is int or type(value) is float:
perperties += "@property (nonatomic, strong) NSNumber *%s;\n" % key
pass
elif type(value) is list:
perperties += "@property (nonatomic, strong) NSArray *%s;\n" % key
if len(value) > 0:
self.generate_objc_properties(edit, value[0], key)
pass
pass
elif type(value) is dict:
self.generate_objc_properties(edit, value, key)
pass
self.view.insert(edit, 0, perperties)
self.view.insert(edit, 0, "\n" + obj_name + ":\n")
pass
@tonycn
Copy link
Author

tonycn commented Apr 12, 2014

Usage:

  1. Open Sublime Console
  2. run command view.run_command("jsonprop")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment