Julia中如何将Dict字符串键转换为同名Type以调用tostruct函数
解决方法
你遇到的核心问题是需要将字符串格式的类型名称映射为Julia中实际的类型对象,可通过getproperty获取对应模块下的类型实现,完整代码如下:
# 你原有定义 jsonDict = Dict( "TypeExample1" => Dict("attr" =>5), "TypeExample2" => Dict("attr" =>10) ) struct TypeExample1 attr end struct TypeExample2 attr end # 自动转换逻辑 instances = Dict() # 用于存储生成的结构体实例 for (key, value) in jsonDict # 将字符串转为符号,从当前主模块获取对应的类型 target_type = getproperty(Main, Symbol(key)) # 调用tostruct生成实例 struct_instance = ToStruct.tostruct(target_type, value) # 存入Dict,后续可以通过类型直接索引取出 instances[target_type] = struct_instance end
补充说明
- 如果你的自定义结构体定义在除了主模块
Main之外的其他自定义模块中,将上述代码中的Main替换为对应模块名即可 - 可增加校验逻辑避免无效key报错:
for (key, value) in jsonDict type_symbol = Symbol(key) if isdefined(Main, type_symbol) target_type = getproperty(Main, type_symbol) instances[target_type] = ToStruct.tostruct(target_type, value) else @warn "未找到对应类型: $key" end end
执行完成后你可以通过instances[TypeExample1]、instances[TypeExample2]直接获取对应的结构体实例。
内容的提问来源于stack exchange,提问作者ahm5
相关产品推荐
相关产品推荐

