csisnett

csisnett

(Protocol.UndefinedError) protocol Jason.Encoder not implemented for %Plug.Conn{adapter: {Plug.Cowboy.Conn, :...}

Hi everyone I’m making an API with phoenix and trying to output json from a struct called Stamp:

defmodule Timestamp.Stamp do
   @derive Jason.Encoder
    defstruct [:unix, :utc]
end

When people access “/api/timestamp/:date” they should get a json like {“unix”: 1921922121, “utc”: “Fri, 25 Dec 2015 00:00:00 GMT”} depending on the date. But the error I receive is the following:

# protocol Jason.Encoder not implemented for %Plug.Conn{adapter: {Plug.Cowboy.Conn, :...}, assigns: %{layout: false, timestmap: %{error: "Invalid Date"}}, before_send: [#Function<1.112466771/1 in Plug.Logger.call/2>, #Function<0.66982185/1 in Phoenix.LiveReloader.before_send_inject_reloader/2>], body_params: %{}, cookies: %Plug.Conn.Unfetched{aspect: :cookies}, halted: false, host: "localhost", method: "GET", owner: #PID<0.529.0>, params: %{"date" => "2"}, path_info: ["api", "timestamp", "2"], path_params: %{"date" => "2"}, port: 4000, private: %{TimestampWeb.Router => {[], %{}}, :phoenix_action => :show, :phoenix_controller => TimestampWeb.DateController, :phoenix_endpoint => TimestampWeb.Endpoint, :phoenix_format => "json", :phoenix_layout => {TimestampWeb.LayoutView, :app}, :phoenix_pipelines => [:api], :phoenix_router => TimestampWeb.Router, :phoenix_template => "show.json", :phoenix_view => TimestampWeb.DateView, :plug_session_fetch => #Function<1.58261320/1 in Plug.Session.fetch_session/1>}, query_params: %{}, query_string: "", remote_ip: {127, 0, 0, 1}, req_cookies: %Plug.Conn.Unfetched{aspect: :cookies}, req_headers: [{"accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}, {"accept-encoding", "gzip, deflate"}, {"accept-language", "en-US,en;q=0.5"}, {"cache-control", "max-age=0"}, {"connection", "keep-alive"}, {"host", "localhost:4000"}, {"upgrade-insecure-requests", "1"}, {"user-agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0"}], request_path: "/api/timestamp/2", resp_body: nil, resp_cookies: %{}, resp_headers: [{"cache-control", "max-age=0, private, must-revalidate"}, {"x-request-id", "2lv5co8o7mv2bndehc0000b4"}], scheme: :http, script_name: [], secret_key_base: :..., state: :unset, status: nil}, Jason.Encoder protocol must always be explicitly implemented.

And the suggestion to add @derive Jason.encoder to the struct module but I already did that.

It also says the protocol is implemented for Timestamp.Stamp, Ecto.Schema.Metadata.. etc, so I’m wondering if I’m missing something

Here is my view and controller:

defmodule TimestampWeb.DateView do
    use TimestampWeb, :view

    def render("show.json", timestamp) do
        timestamp
    end
end

defmodule TimestampWeb.DateController do
    use TimestampWeb, :controller

    alias Timestamp.Implementation
    def show(conn, %{"date" => date}) do
        timestamp = Implementation.get_timestamp(date)
        render(conn, "show.json", timestmap: timestamp)
    end
end

And my router:

defmodule TimestampWeb.Router do
....

  scope "/api/timestamp", TimestampWeb do
    pipe_through :api

    get "/:date", DateController, :show
    get "/", CurrentTimestampController, :show
  end

end

Most Liked

gcauchon

gcauchon

It looks like your code wants to serialize the whole Plug.Conn struct, not the %Timestamp.Stamp{…} returned by TimestampWeb.DateView.render/2?!

You might need to pattern match on timestamp on the second argument since the invocation in Timestamp.Implementation.show/2 uses the keyword list shorthand.

csisnett

csisnett

Thank you @gcauchon when I pattern matched timestamp like:

defmodule TimestampWeb.DateView do
use TimestampWeb, :view
alias Timestamp.Stamp

def render("show.json", %{timestamp: timestamp}) do
    timestamp
end

end

it worked!

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement