Best practice for JSON foreign key references?

717 views
Skip to first unread message

Patrick Lightbody

unread,
Mar 6, 2013, 10:11:19 AM3/6/13
to play-fr...@googlegroups.com
Suppose I have two models: Foo and Bar. Bar is already in the database with an instance with ID 123. In building out a REST API, I want to allow the API to accept a JSON representation of Foo, including the reference to the "123" instance of Bar.

This would obviously be bad:

{ fooProp1: "...", fooProp2: "...", bar: { id: 123, barProp1: "..." } }

Instead I'd prefer something like:

{ fooProp1: "...", fooProp2: "...", bar: 123 }

Of course, when I run this through Json.fromJson(json, Foo.class), it blows up complaining that "123" can't be converted to Bar. I have used Jackson directly before and what I'd normally do is register a converter that would do the mapping for me and call Bar.find.byId() on my behalf. So two questions:

1) Is this possible?

2) Is it a best practice? If not, what is the recommended way to do this kind of stuff.

Thanks!

Patrick

Pascal Voitot Dev

unread,
Mar 6, 2013, 10:13:03 AM3/6/13
to play-fr...@googlegroups.com
in scala or java?

Pascal



Patrick

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framewor...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Patrick Lightbody

unread,
Mar 6, 2013, 10:15:55 AM3/6/13
to play-fr...@googlegroups.com
Apologies: this is Java using Play 2.0. Missed the request for subject line clarification until after I posted :)

You received this message because you are subscribed to a topic in the Google Groups "play-framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/play-framework/DBZ0bFDyHjI/unsubscribe?hl=en-US.
To unsubscribe from this group and all its topics, send an email to play-framewor...@googlegroups.com.

Pascal Voitot Dev

unread,
Mar 6, 2013, 11:01:06 AM3/6/13
to play-fr...@googlegroups.com
So I don't have your anwer and I'd say it's in Jackson IMO.
Maybe someone else has the answer in the community ;)

Pascal

Guillaume Bort

unread,
Mar 6, 2013, 11:12:44 AM3/6/13
to play-fr...@googlegroups.com
On Wed, Mar 6, 2013 at 4:11 PM, Patrick Lightbody <pat...@lightbody.net> wrote:
Of course, when I run this through Json.fromJson(json, Foo.class), it blows up complaining that "123" can't be converted to Bar. I have used Jackson directly before and what I'd normally do is register a converter that would do the mapping for me and call Bar.find.byId() on my behalf. So two questions:

1) Is this possible?

You are free to use Jackson directly. `Json.fromJson` is just a more direct helper for simple use cases.


--
Guillaume Bort, http://guillaume.bort.fr
Reply all
Reply to author
Forward
0 new messages