proper indention for swift generator

This commit is contained in:
wing328 2016-03-02 15:46:24 +08:00
parent 7a7265b0d7
commit 057e1d4c4b
5 changed files with 528 additions and 528 deletions

View File

@ -24,396 +24,396 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PROJECT_NAME = "projectName"; public static final String PROJECT_NAME = "projectName";
public static final String RESPONSE_AS = "responseAs"; public static final String RESPONSE_AS = "responseAs";
public static final String UNWRAP_REQUIRED = "unwrapRequired"; public static final String UNWRAP_REQUIRED = "unwrapRequired";
public static final String POD_SOURCE = "podSource"; public static final String POD_SOURCE = "podSource";
public static final String POD_AUTHORS = "podAuthors"; public static final String POD_AUTHORS = "podAuthors";
public static final String POD_SOCIAL_MEDIA_URL = "podSocialMediaURL"; public static final String POD_SOCIAL_MEDIA_URL = "podSocialMediaURL";
public static final String POD_DOCSET_URL = "podDocsetURL"; public static final String POD_DOCSET_URL = "podDocsetURL";
public static final String POD_LICENSE = "podLicense"; public static final String POD_LICENSE = "podLicense";
public static final String POD_HOMEPAGE = "podHomepage"; public static final String POD_HOMEPAGE = "podHomepage";
public static final String POD_SUMMARY = "podSummary"; public static final String POD_SUMMARY = "podSummary";
public static final String POD_DESCRIPTION = "podDescription"; public static final String POD_DESCRIPTION = "podDescription";
public static final String POD_SCREENSHOTS = "podScreenshots"; public static final String POD_SCREENSHOTS = "podScreenshots";
public static final String POD_DOCUMENTATION_URL = "podDocumentationURL"; public static final String POD_DOCUMENTATION_URL = "podDocumentationURL";
public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace"; public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace";
protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; protected static final String LIBRARY_PROMISE_KIT = "PromiseKit";
protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT }; protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT };
protected String projectName = "SwaggerClient"; protected String projectName = "SwaggerClient";
protected boolean unwrapRequired; protected boolean unwrapRequired;
protected boolean swiftUseApiNamespace; protected boolean swiftUseApiNamespace;
protected String[] responseAs = new String[0]; protected String[] responseAs = new String[0];
protected String sourceFolder = "Classes" + File.separator + "Swaggers"; protected String sourceFolder = "Classes" + File.separator + "Swaggers";
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
@Override @Override
public CodegenType getTag() { public CodegenType getTag() {
return CodegenType.CLIENT; return CodegenType.CLIENT;
} }
@Override @Override
public String getName() { public String getName() {
return "swift"; return "swift";
} }
@Override @Override
public String getHelp() { public String getHelp() {
return "Generates a swift client library."; return "Generates a swift client library.";
} }
public SwiftCodegen() { public SwiftCodegen() {
super(); super();
outputFolder = "generated-code" + File.separator + "swift"; outputFolder = "generated-code" + File.separator + "swift";
modelTemplateFiles.put("model.mustache", ".swift"); modelTemplateFiles.put("model.mustache", ".swift");
apiTemplateFiles.put("api.mustache", ".swift"); apiTemplateFiles.put("api.mustache", ".swift");
embeddedTemplateDir = templateDir = "swift"; embeddedTemplateDir = templateDir = "swift";
apiPackage = File.separator + "APIs"; apiPackage = File.separator + "APIs";
modelPackage = File.separator + "Models"; modelPackage = File.separator + "Models";
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"Int", "Int",
"Float", "Float",
"Double", "Double",
"Bool", "Bool",
"Void", "Void",
"String", "String",
"Character", "Character",
"AnyObject") "AnyObject")
); );
defaultIncludes = new HashSet<String>( defaultIncludes = new HashSet<String>(
Arrays.asList( Arrays.asList(
"NSDate", "NSDate",
"Array", "Array",
"Dictionary", "Dictionary",
"Set", "Set",
"Any", "Any",
"Empty", "Empty",
"AnyObject") "AnyObject")
); );
setReservedWordsLowerCase( setReservedWordsLowerCase(
Arrays.asList( Arrays.asList(
"class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue",
"false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else",
"self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if",
"true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol",
"switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional",
"struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol",
"required", "right", "set", "Type", "unowned", "weak") "required", "right", "set", "Type", "unowned", "weak")
); );
typeMapping = new HashMap<String, String>(); typeMapping = new HashMap<String, String>();
typeMapping.put("array", "Array"); typeMapping.put("array", "Array");
typeMapping.put("List", "Array"); typeMapping.put("List", "Array");
typeMapping.put("map", "Dictionary"); typeMapping.put("map", "Dictionary");
typeMapping.put("date", "NSDate"); typeMapping.put("date", "NSDate");
typeMapping.put("Date", "NSDate"); typeMapping.put("Date", "NSDate");
typeMapping.put("DateTime", "NSDate"); typeMapping.put("DateTime", "NSDate");
typeMapping.put("boolean", "Bool"); typeMapping.put("boolean", "Bool");
typeMapping.put("string", "String"); typeMapping.put("string", "String");
typeMapping.put("char", "Character"); typeMapping.put("char", "Character");
typeMapping.put("short", "Int"); typeMapping.put("short", "Int");
typeMapping.put("int", "Int"); typeMapping.put("int", "Int");
typeMapping.put("long", "Int"); typeMapping.put("long", "Int");
typeMapping.put("integer", "Int"); typeMapping.put("integer", "Int");
typeMapping.put("Integer", "Int"); typeMapping.put("Integer", "Int");
typeMapping.put("float", "Float"); typeMapping.put("float", "Float");
typeMapping.put("number", "Double"); typeMapping.put("number", "Double");
typeMapping.put("double", "Double"); typeMapping.put("double", "Double");
typeMapping.put("object", "AnyObject"); typeMapping.put("object", "AnyObject");
typeMapping.put("file", "NSURL"); typeMapping.put("file", "NSURL");
//TODO binary should be mapped to byte array //TODO binary should be mapped to byte array
// mapped to String as a workaround // mapped to String as a workaround
typeMapping.put("binary", "String"); typeMapping.put("binary", "String");
importMapping = new HashMap<String, String>(); importMapping = new HashMap<String, String>();
cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode")); cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode"));
cliOptions.add(new CliOption(RESPONSE_AS, "Optionally use libraries to manage response. Currently " + cliOptions.add(new CliOption(RESPONSE_AS, "Optionally use libraries to manage response. Currently " +
StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available."));
cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " + cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " +
"(which would crash the app if api returns null as opposed to required option specified in json schema")); "(which would crash the app if api returns null as opposed to required option specified in json schema"));
cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec")); cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec"));
cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec")); cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec"));
cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec")); cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec"));
cliOptions.add(new CliOption(POD_SOCIAL_MEDIA_URL, "Social Media URL used for Podspec")); cliOptions.add(new CliOption(POD_SOCIAL_MEDIA_URL, "Social Media URL used for Podspec"));
cliOptions.add(new CliOption(POD_DOCSET_URL, "Docset URL used for Podspec")); cliOptions.add(new CliOption(POD_DOCSET_URL, "Docset URL used for Podspec"));
cliOptions.add(new CliOption(POD_LICENSE, "License used for Podspec")); cliOptions.add(new CliOption(POD_LICENSE, "License used for Podspec"));
cliOptions.add(new CliOption(POD_HOMEPAGE, "Homepage used for Podspec")); cliOptions.add(new CliOption(POD_HOMEPAGE, "Homepage used for Podspec"));
cliOptions.add(new CliOption(POD_SUMMARY, "Summary used for Podspec")); cliOptions.add(new CliOption(POD_SUMMARY, "Summary used for Podspec"));
cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec")); cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec"));
cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec"));
cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec"));
cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API")); cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE, "Flag to make all the API classes inner-class of {{projectName}}API"));
}
@Override
public void processOpts() {
super.processOpts();
// Setup project name
if (additionalProperties.containsKey(PROJECT_NAME)) {
setProjectName((String) additionalProperties.get(PROJECT_NAME));
} else {
additionalProperties.put(PROJECT_NAME, projectName);
}
sourceFolder = projectName + File.separator + sourceFolder;
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(UNWRAP_REQUIRED)) {
setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED))));
}
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
// Setup unwrapRequired option, which makes all the properties with "required" non-optional
if (additionalProperties.containsKey(RESPONSE_AS)) {
Object responseAsObject = additionalProperties.get(RESPONSE_AS);
if (responseAsObject instanceof String) {
setResponseAs(((String)responseAsObject).split(","));
} else {
setResponseAs((String[]) responseAsObject);
}
}
additionalProperties.put(RESPONSE_AS, responseAs);
if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) {
additionalProperties.put("usePromiseKit", true);
} }
// Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API @Override
if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { public void processOpts() {
swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE))); super.processOpts();
}
additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace);
supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); // Setup project name
supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); if (additionalProperties.containsKey(PROJECT_NAME)) {
supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); setProjectName((String) additionalProperties.get(PROJECT_NAME));
supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, } else {
"AlamofireImplementations.swift")); additionalProperties.put(PROJECT_NAME, projectName);
supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); }
supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); sourceFolder = projectName + File.separator + sourceFolder;
supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift"));
}
@Override // Setup unwrapRequired option, which makes all the properties with "required" non-optional
public String escapeReservedWord(String name) { if (additionalProperties.containsKey(UNWRAP_REQUIRED)) {
return "_" + name; // add an underscore to the name setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED))));
} }
additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired);
@Override // Setup unwrapRequired option, which makes all the properties with "required" non-optional
public String modelFileFolder() { if (additionalProperties.containsKey(RESPONSE_AS)) {
return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar); Object responseAsObject = additionalProperties.get(RESPONSE_AS);
} if (responseAsObject instanceof String) {
setResponseAs(((String)responseAsObject).split(","));
} else {
setResponseAs((String[]) responseAsObject);
}
}
additionalProperties.put(RESPONSE_AS, responseAs);
if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) {
additionalProperties.put("usePromiseKit", true);
}
@Override // Setup swiftUseApiNamespace option, which makes all the API classes inner-class of {{projectName}}API
public String apiFileFolder() { if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
return outputFolder + File.separator + sourceFolder + apiPackage().replace('.', File.separatorChar); swiftUseApiNamespace = Boolean.parseBoolean(String.valueOf(additionalProperties.get(SWIFT_USE_API_NAMESPACE)));
} }
additionalProperties.put(SWIFT_USE_API_NAMESPACE, swiftUseApiNamespace);
@Override supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec"));
public String getTypeDeclaration(Property p) { supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile"));
if (p instanceof ArrayProperty) { supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift"));
ArrayProperty ap = (ArrayProperty) p; supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder,
Property inner = ap.getItems(); "AlamofireImplementations.swift"));
return "[" + getTypeDeclaration(inner) + "]"; supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift"));
} else if (p instanceof MapProperty) { supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift"));
MapProperty mp = (MapProperty) p; supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift"));
Property inner = mp.getAdditionalProperties(); }
return "[String:" + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
@Override @Override
public String getSwaggerType(Property p) { public String escapeReservedWord(String name) {
String swaggerType = super.getSwaggerType(p); return "_" + name; // add an underscore to the name
String type = null; }
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
@Override @Override
public String toDefaultValue(Property p) { public String modelFileFolder() {
// nil return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar);
return null; }
}
@Override @Override
public String toInstantiationType(Property p) { public String apiFileFolder() {
if (p instanceof MapProperty) { return outputFolder + File.separator + sourceFolder + apiPackage().replace('.', File.separatorChar);
MapProperty ap = (MapProperty) p; }
String inner = getSwaggerType(ap.getAdditionalProperties());
return "[String:" + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "[" + inner + "]";
}
return null;
}
@Override @Override
public CodegenProperty fromProperty(String name, Property p) { public String getTypeDeclaration(Property p) {
CodegenProperty codegenProperty = super.fromProperty(name, p); if (p instanceof ArrayProperty) {
if (codegenProperty.isEnum) { ArrayProperty ap = (ArrayProperty) p;
List<Map<String, String>> swiftEnums = new ArrayList<Map<String, String>>(); Property inner = ap.getItems();
List<String> values = (List<String>) codegenProperty.allowableValues.get("values"); return "[" + getTypeDeclaration(inner) + "]";
for (String value : values) { } else if (p instanceof MapProperty) {
Map<String, String> map = new HashMap<String, String>(); MapProperty mp = (MapProperty) p;
map.put("enum", toSwiftyEnumName(value)); Property inner = mp.getAdditionalProperties();
map.put("raw", value); return "[String:" + getTypeDeclaration(inner) + "]";
swiftEnums.add(map); }
} return super.getTypeDeclaration(p);
codegenProperty.allowableValues.put("values", swiftEnums); }
codegenProperty.datatypeWithEnum =
StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); @Override
// Ensure that the enum type doesn't match a reserved word or public String getSwaggerType(Property p) {
// the variable name doesn't match the generated enum type or the String swaggerType = super.getSwaggerType(p);
// Swift compiler will generate an error String type = null;
if (isReservedWord(codegenProperty.datatypeWithEnum) || if (typeMapping.containsKey(swaggerType)) {
name.equals(codegenProperty.datatypeWithEnum)) { type = typeMapping.get(swaggerType);
codegenProperty.datatypeWithEnum = escapeReservedWord(codegenProperty.datatypeWithEnum); if (languageSpecificPrimitives.contains(type))
} return toModelName(type);
} } else
return codegenProperty; type = swaggerType;
} return toModelName(type);
}
@Override
public String toDefaultValue(Property p) {
// nil
return null;
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "[String:" + inner + "]";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "[" + inner + "]";
}
return null;
}
@Override
public CodegenProperty fromProperty(String name, Property p) {
CodegenProperty codegenProperty = super.fromProperty(name, p);
if (codegenProperty.isEnum) {
List<Map<String, String>> swiftEnums = new ArrayList<Map<String, String>>();
List<String> values = (List<String>) codegenProperty.allowableValues.get("values");
for (String value : values) {
Map<String, String> map = new HashMap<String, String>();
map.put("enum", toSwiftyEnumName(value));
map.put("raw", value);
swiftEnums.add(map);
}
codegenProperty.allowableValues.put("values", swiftEnums);
codegenProperty.datatypeWithEnum =
StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length());
// Ensure that the enum type doesn't match a reserved word or
// the variable name doesn't match the generated enum type or the
// Swift compiler will generate an error
if (isReservedWord(codegenProperty.datatypeWithEnum) ||
name.equals(codegenProperty.datatypeWithEnum)) {
codegenProperty.datatypeWithEnum = escapeReservedWord(codegenProperty.datatypeWithEnum);
}
}
return codegenProperty;
}
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
public String toSwiftyEnumName(String value) { public String toSwiftyEnumName(String value) {
// Prevent from breaking properly cased identifier // Prevent from breaking properly cased identifier
if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
return value; return value;
}
char[] separators = {'-', '_', ' '};
return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", "");
} }
char[] separators = {'-', '_', ' '};
return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", "");
@Override
public String toApiName(String name) {
if(name.length() == 0)
return "DefaultAPI";
return initialCaps(name) + "API";
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(sanitizeName(operationId), true);
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// sanitize name
name = sanitizeName(name);
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize(lower) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override
public boolean apply(@Nullable Parameter parameter) {
return !(parameter instanceof HeaderParameter);
}
}));
operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions, swagger);
}
private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
int cursor = 0;
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
boolean found = matcher.find();
while (found) {
String stringBeforeMatch = path.substring(cursor, matcher.start());
builder.append(stringBeforeMatch);
String group = matcher.group().substring(1, matcher.group().length() - 1);
group = camelize(group, true);
builder
.append("{")
.append(group)
.append("}");
cursor = matcher.end();
found = matcher.find();
}
String stringAfterMatch = path.substring(cursor);
builder.append(stringAfterMatch);
return builder.toString();
} }
public void setProjectName(String projectName) {
@Override this.projectName = projectName;
public String toApiName(String name) {
if(name.length() == 0)
return "DefaultAPI";
return initialCaps(name) + "API";
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
} }
// method name cannot use reserved keyword, e.g. return public void setUnwrapRequired(boolean unwrapRequired) {
if (isReservedWord(operationId)) { this.unwrapRequired = unwrapRequired;
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
} }
return camelize(sanitizeName(operationId), true); public void setResponseAs(String[] responseAs) {
} this.responseAs = responseAs;
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
} }
// camelize the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// sanitize name
name = sanitizeName(name);
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize(lower) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@Override
public boolean apply(@Nullable Parameter parameter) {
return !(parameter instanceof HeaderParameter);
}
}));
operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions, swagger);
}
private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
int cursor = 0;
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
boolean found = matcher.find();
while (found) {
String stringBeforeMatch = path.substring(cursor, matcher.start());
builder.append(stringBeforeMatch);
String group = matcher.group().substring(1, matcher.group().length() - 1);
group = camelize(group, true);
builder
.append("{")
.append(group)
.append("}");
cursor = matcher.end();
found = matcher.find();
}
String stringAfterMatch = path.substring(cursor);
builder.append(stringAfterMatch);
return builder.toString();
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public void setUnwrapRequired(boolean unwrapRequired) {
this.unwrapRequired = unwrapRequired;
}
public void setResponseAs(String[] responseAs) {
this.responseAs = responseAs;
}
} }

View File

@ -166,20 +166,20 @@ public class PetAPI: APIBase {
- OAuth: - OAuth:
- type: oauth2 - type: oauth2
- name: petstore_auth - name: petstore_auth
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -188,21 +188,21 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -211,7 +211,7 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- parameter status: (query) Status values that need to be considered for query - parameter status: (query) Status values that need to be considered for query
@ -272,20 +272,20 @@ public class PetAPI: APIBase {
- OAuth: - OAuth:
- type: oauth2 - type: oauth2
- name: petstore_auth - name: petstore_auth
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -294,21 +294,21 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], } ], contentType=application/json}, {example=<Pet>
"status" : "aeiou"
} ]}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -317,7 +317,7 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- parameter tags: (query) Tags to filter by - parameter tags: (query) Tags to filter by
@ -375,26 +375,26 @@ public class PetAPI: APIBase {
- GET /pet/{petId} - GET /pet/{petId}
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
- OAuth:
- type: oauth2
- name: petstore_auth
- API Key: - API Key:
- type: apiKey api_key - type: apiKey api_key
- name: api_key - name: api_key
- examples: [{contentType=application/json, example={ - OAuth:
"photoUrls" : [ "aeiou" ], - type: oauth2
"name" : "doggie", - name: petstore_auth
- examples: [{example={
"tags" : [ {
"id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], }, contentType=application/json}, {example=<Pet>
"status" : "aeiou"
}}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -403,21 +403,21 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"photoUrls" : [ "aeiou" ], "tags" : [ {
"name" : "doggie", "id" : 123456789,
"name" : "aeiou"
} ],
"id" : 123456789, "id" : 123456789,
"category" : { "category" : {
"name" : "aeiou", "id" : 123456789,
"id" : 123456789 "name" : "aeiou"
}, },
"tags" : [ { "status" : "aeiou",
"name" : "aeiou", "name" : "doggie",
"id" : 123456789 "photoUrls" : [ "aeiou" ]
} ], }, contentType=application/json}, {example=<Pet>
"status" : "aeiou"
}}, {contentType=application/xml, example=<Pet>
<id>123456</id> <id>123456</id>
<name>doggie</name> <name>doggie</name>
<photoUrls> <photoUrls>
@ -426,7 +426,7 @@ public class PetAPI: APIBase {
<tags> <tags>
</tags> </tags>
<status>string</status> <status>string</status>
</Pet>}] </Pet>, contentType=application/xml}]
- parameter petId: (path) ID of pet that needs to be fetched - parameter petId: (path) ID of pet that needs to be fetched
@ -678,14 +678,14 @@ public class PetAPI: APIBase {
- GET /pet/{petId}?testing_byte_array=true - GET /pet/{petId}?testing_byte_array=true
- Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
- OAuth:
- type: oauth2
- name: petstore_auth
- API Key: - API Key:
- type: apiKey api_key - type: apiKey api_key
- name: api_key - name: api_key
- examples: [{contentType=application/json, example=""}, {contentType=application/xml, example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e}] - OAuth:
- examples: [{contentType=application/json, example=""}, {contentType=application/xml, example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e}] - type: oauth2
- name: petstore_auth
- examples: [{example="", contentType=application/json}, {example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e, contentType=application/xml}]
- examples: [{example="", contentType=application/json}, {example=not implemented io.swagger.models.properties.BinaryProperty@55e6ae9e, contentType=application/xml}]
- parameter petId: (path) ID of pet that needs to be fetched - parameter petId: (path) ID of pet that needs to be fetched

View File

@ -55,36 +55,36 @@ public class StoreAPI: APIBase {
- API Key: - API Key:
- type: apiKey x-test_api_client_secret - type: apiKey x-test_api_client_secret
- name: test_api_client_secret - name: test_api_client_secret
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+0000", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
} ]}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+0000"
} ], contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- examples: [{contentType=application/json, example=[ { - examples: [{example=[ {
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+0000", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
} ]}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+0000"
} ], contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- parameter status: (query) Status value that needs to be considered for query - parameter status: (query) Status value that needs to be considered for query
@ -143,12 +143,12 @@ public class StoreAPI: APIBase {
- API Key: - API Key:
- type: apiKey api_key - type: apiKey api_key
- name: api_key - name: api_key
- examples: [{contentType=application/json, example={ - examples: [{example={
"key" : 123 "key" : 123
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] }, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"key" : 123 "key" : 123
}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] }, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}]
- returns: RequestBuilder<[String:Int]> - returns: RequestBuilder<[String:Int]>
*/ */
@ -208,36 +208,36 @@ public class StoreAPI: APIBase {
- API Key: - API Key:
- type: apiKey x-test_api_client_secret - type: apiKey x-test_api_client_secret
- name: test_api_client_secret - name: test_api_client_secret
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+0000", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+0000"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+0000", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+0000"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- parameter body: (body) order placed for purchasing the pet - parameter body: (body) order placed for purchasing the pet
@ -292,42 +292,42 @@ public class StoreAPI: APIBase {
- GET /store/order/{orderId} - GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- API Key:
- type: apiKey test_api_key_query (QUERY)
- name: test_api_key_query
- API Key: - API Key:
- type: apiKey test_api_key_header - type: apiKey test_api_key_header
- name: test_api_key_header - name: test_api_key_header
- examples: [{contentType=application/json, example={ - API Key:
"petId" : 123456789, - type: apiKey test_api_key_query (QUERY)
"quantity" : 123, - name: test_api_key_query
- examples: [{example={
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+0000", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+0000"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- examples: [{contentType=application/json, example={ - examples: [{example={
"petId" : 123456789,
"quantity" : 123,
"id" : 123456789, "id" : 123456789,
"shipDate" : "2000-01-23T04:56:07.000+0000", "petId" : 123456789,
"complete" : true, "complete" : true,
"status" : "aeiou" "status" : "aeiou",
}}, {contentType=application/xml, example=<Order> "quantity" : 123,
"shipDate" : "2000-01-23T04:56:07.000+0000"
}, contentType=application/json}, {example=<Order>
<id>123456</id> <id>123456</id>
<petId>123456</petId> <petId>123456</petId>
<quantity>0</quantity> <quantity>0</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate> <shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>string</status> <status>string</status>
<complete>true</complete> <complete>true</complete>
</Order>}] </Order>, contentType=application/xml}]
- parameter orderId: (path) ID of pet that needs to be fetched - parameter orderId: (path) ID of pet that needs to be fetched

View File

@ -213,8 +213,8 @@ public class UserAPI: APIBase {
- GET /user/login - GET /user/login
- -
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}]
- parameter username: (query) The user name for login - parameter username: (query) The user name for login
- parameter password: (query) The password for login in clear text - parameter password: (query) The password for login in clear text
@ -325,7 +325,7 @@ public class UserAPI: APIBase {
- GET /user/{username} - GET /user/{username}
- -
- examples: [{contentType=application/json, example={ - examples: [{example={
"id" : 1, "id" : 1,
"username" : "johnp", "username" : "johnp",
"firstName" : "John", "firstName" : "John",
@ -334,7 +334,7 @@ public class UserAPI: APIBase {
"password" : "-secret-", "password" : "-secret-",
"phone" : "0123456789", "phone" : "0123456789",
"userStatus" : 0 "userStatus" : 0
}}] }, contentType=application/json}]
- parameter username: (path) The name that needs to be fetched. Use user1 for testing. - parameter username: (path) The name that needs to be fetched. Use user1 for testing.

View File

@ -124,24 +124,6 @@ class Decoders {
fatalError("formatter failed to parse \(source)") fatalError("formatter failed to parse \(source)")
} }
// Decoder for [Order]
Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in
return Decoders.decode(clazz: [Order].self, source: source)
}
// Decoder for Order
Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = Order()
instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"])
instance.petId = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["petId"])
instance.quantity = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["quantity"])
instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"])
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"])
return instance
}
// Decoder for [User] // Decoder for [User]
Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in
return Decoders.decode(clazz: [User].self, source: source) return Decoders.decode(clazz: [User].self, source: source)
@ -176,20 +158,6 @@ class Decoders {
} }
// Decoder for [Tag]
Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in
return Decoders.decode(clazz: [Tag].self, source: source)
}
// Decoder for Tag
Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = Tag()
instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"])
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
return instance
}
// Decoder for [Pet] // Decoder for [Pet]
Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in
return Decoders.decode(clazz: [Pet].self, source: source) return Decoders.decode(clazz: [Pet].self, source: source)
@ -207,6 +175,38 @@ class Decoders {
return instance return instance
} }
// Decoder for [Tag]
Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in
return Decoders.decode(clazz: [Tag].self, source: source)
}
// Decoder for Tag
Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = Tag()
instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"])
instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"])
return instance
}
// Decoder for [Order]
Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in
return Decoders.decode(clazz: [Order].self, source: source)
}
// Decoder for Order
Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in
let sourceDictionary = source as! [NSObject:AnyObject]
let instance = Order()
instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"])
instance.petId = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["petId"])
instance.quantity = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["quantity"])
instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"])
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"])
return instance
}
} }
} }
} }