亲爱的 Stackoverflowers,
我在使用 ObjectMapper 方面遇到了障碍,所以让我们开门见山。
我将模型以 JSON 格式保存为 SQLite 表中的临时记录。每个模型都有一个类型字段,用于唯一标识它映射到的模型类型。
例如,如果我们有符合 Animal 协议(protocol)的模型 Dog、Cat、Mouse,则有一个等效的 AnimalType (DogType、CatType、MouseType) 枚举,它也是每个模型中的一个字段。保存到数据库后,我很难找到一种优雅的方式来将从数据库加载的 JSON 映射到 Model 类的实际实例。
我目前正在做的是通过 NSJSONSerialization 将 JSON 转换为 JSON 字典并在字典中查询类型。找到类型后,我会切换所有类型,实例化相关的 Mapper 对象并尝试反序列化该对象。我觉得这是一种蛮力方法,并且认为可能有更好的方法来解决这个问题。
结论性的:
模型:Dog、Cat、Mouse(符合Animal,有AnimalType要求)
枚举:AnimalType(DogType、CatType、MouseType)
问题:如何确定并正确实例化 Mapper 对象以将加载的 JSON 反序列化为实例,而不是手动检查每个类型并实例化正确的映射器。
enum AnimalType {
case Dog
case Cat
case Mouse
}
protocol Animal {
var animalType: AnimalType { get }
}
struct Dog: Animal {
var animalType = AnimalType.Dog
}
struct Cat: Animal {
var animalType = AnimalType.Cat
}
struct Mouse: Animal {
var animalType = AnimalType.Mouse
}
最佳答案
import ObjectMapper
enum AnimalType : String {
case Cat = "Cat"
case Dog = "Dog"
case Mouse = "Mouse"
}
class Animal: StaticMappable, Mappable {
var animalType: AnimalType?
required init?(_ map: Map) {}
init() {}
func mapping(map: Map) {
animalType <- (map["animalType"], EnumTransform<AnimalType>())
}
static func objectForMapping(map: Map) -> BaseMappable? {
let typeString: String? = map["animalType"].value()
if let typeString = typeString {
let animalType: AnimalType? = AnimalType(rawValue: typeString)
if let animalType = animalType {
switch(animalType) {
case AnimalType.Cat: return Cat()
case AnimalType.Dog: return Dog()
case AnimalType.Mouse: return Mouse()
}
}
}
return Animal()
}
}
class Cat: Animal {
var purr: String?
required init?(_ map: Map) {
super.init(map)
}
override init() {
super.init()
}
override func mapping(map: Map) {
super.mapping(map)
purr <- map["purr"]
}
}
class Dog: Animal {
var bark: String?
var bite: String?
required init?(_ map: Map) {
super.init(map)
}
override init() {
super.init()
}
override func mapping(map: Map) {
super.mapping(map)
bark <- map["bark"]
bite <- map["bite"]
}
}
class Mouse: Animal {
var squeak: String?
required init?(_ map: Map) {
super.init(map)
}
override init() {
super.init()
}
override func mapping(map: Map) {
super.mapping(map)
squeak <- map["squeak"]
}
}
class Owner : Mappable {
var name: String?
var animal: Animal?
required init?(_ map: Map) {}
func mapping(map: Map) {
name <- map["name"]
animal <- map["animal"]
}
}
let catJson = "{\"animalType\":\"Cat\",\"purr\":\"rrurrrrrurrr\"}"
let cat = Mapper<Cat>().map(catJson)
if let cat = cat {
let catJSONString = Mapper().toJSONString(cat, prettyPrint: false)
}
let ownerJson = "{\"name\":\"Blofeld\", \"animal\":{\"animalType\":\"Cat\",\"purr\":\"rrurrrrrurrr\"}}"
let owner = Mapper<Owner>().map(ownerJson)
if let owner = owner {
let ownerJSONString = Mapper().toJSONString(owner, prettyPrint: false)
}
我在寻找 Jackson 的 @JsonSubTypes 的 Swift 等价物时写了这篇文章,用于 JSON 子类的多态映射。
关于ios - Swift ObjectMapper 类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37006620/
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
我想使用PostgreSQL中的point类型。我已经完成了:railsgmodelTestpoint:point最终的迁移是:classCreateTests当我运行时:rakedb:migrate结果是:==CreateTests:migrating====================================================--create_table(:tests)rakeaborted!Anerrorhasoccurred,thisandalllatermigrationscanceled:undefinedmethod`point'for#/hom