Created
June 9, 2013 09:30
-
-
Save douo/8ef553eaad1b30e921e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require 'json' | |
str = '{"a":"string","b":12,"c":2.12,"d":9223372036854775807,"e":0.142318719237491324918231415143121324,"f":[1,3,4,5,6] }' | |
class JavaGenerator | |
def initialize(name, config={}) | |
@name = name | |
@config = config | |
@baseJavaType = | |
{ | |
"String" => "String", | |
"Fixnum" => "int", | |
"Bignum" => "long", | |
"Float" => "double", | |
"TrueClass" => "boolean", | |
"FalseClass" => "boolean" | |
} | |
@baseImport = [ | |
"import org.json.*;", | |
"import java.util.*;" | |
] | |
end | |
def parse(json) | |
@members = [] | |
json.each {|k,v| @members << {"name" => "#{k}","type" => "#{toType(k,v)}"}} | |
end | |
def toType(name,type) | |
className = type.class.to_s | |
if className == "Hash" | |
## TODO 建立子类 | |
## 返回类目作为类型名 | |
return name.capitalize | |
end | |
if className == "Array" | |
## TODO 遍历数组 检查类型。返回泛型数组 | |
return "ArrayList<#{name.capitalize}>" | |
end | |
return @baseJavaType[className] | |
end | |
def to_s | |
super + "#{@name}\nMembers:#{@members}" | |
end | |
end | |
j = JavaGenerator.new("test") | |
j.parse(JSON.parse(str)) | |
puts j |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment