我尝试将map转换为struct,如下所示:
我有一张地图:
iex(6)> user
%{"basic_auth" => "Basic Ym1hOmphYnJhMTc=", "firstname" => "foo",
"lastname" => "boo"}该值应应用于struct:
iex(7)> a = struct(UserInfo, user)
%SapOdataService.Auth.UserInfo{basic_auth: nil, firstname: nil, lastname: nil}正如你所看到的,struct的值是空的,为什么呢?
发布于 2017-02-01 21:20:29
要扩展JustMichael的答案,您可以首先使用String.to_existing_atom/1将键转换为原子,然后使用Kernel.struct/2来构建结构:
user_with_atom_keys = for {key, val} <- user, into: %{} do
{String.to_existing_atom(key), val}
end
user_struct = struct(UserInfo, user_with_atom_keys)
# %UserInfo{basic_auth: "Basic Ym1hOmphYnJhMTc=", firstname: "foo",
lastname: "boo"}请注意,这使用String.to_existing_atom/1来防止VM达到全局Atom限制。
发布于 2017-02-01 21:05:51
我的猜测是它不起作用,因为你在map中有键作为字符串,在struct中有原子。
发布于 2017-02-01 21:18:15
你可以试试exconstructor。它做的正是你需要的。
下面是一个小示例:
defmodule TestStruct do
defstruct field_one: nil,
field_two: nil,
field_three: nil,
field_four: nil
use ExConstructor
end
TestStruct.new(%{"field_one" => "a", "fieldTwo" => "b", :field_three => "c", :FieldFour => "d"})
# => %TestStruct{field_one: "a", field_two: "b", field_three: "c", field_four: "d"}文档链接:http://hexdocs.pm/exconstructor/ExConstructor.html
https://stackoverflow.com/questions/41980358
复制相似问题