# Advanced use of to\_xml and to\_json

**URL:** <https://www.ruby-forum.com/t/advanced-use-of-to-xml-and-to-json/183807>\
**Category:** Rails\
**Created:** [February 20, 2010, 5:15pm UTC](https://www.ruby-forum.com/t/advanced-use-of-to-xml-and-to-json/183807 "2010-02-20T17:15:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![camilleroux](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/4491bb/32.png) [@camilleroux](https://www.ruby-forum.com/u/camilleroux)\
**Post date:** [February 20, 2010, 5:15pm UTC](https://www.ruby-forum.com/t/advanced-use-of-to-xml-and-to-json/183807/1 "2010-02-20T17:15:24Z")

</div>

Hello,

I’m working on a Rails app which has a REST API. I manage two formats  
JSON and XML.  
Very often to simplify the use if the API, I’m making includes. But when  
you add params to to\_json and to\_xml like :only, :except, it’s not only  
applied on the root object but on all the objects included.

Do you know libs or methods to answer to these different problems:

- Tell never return a user password in the API
- Tell always include a relationship or a method in each user serialized  
in the API
- Serialize objects depending on context. For exemple, when a user ask  
for the user list, he should see its complete profile, a partial profile  
of its friends and just the name of others…
- Don’t have to copy paste the parameters for xml and json

Thank you very much,  
Camille R.

---

<div class="post-metadata">

**Author:** ![camilleroux](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/4491bb/32.png) [@camilleroux](https://www.ruby-forum.com/u/camilleroux)\
**Post date:** [February 20, 2010, 8:00pm UTC](https://www.ruby-forum.com/t/advanced-use-of-to-xml-and-to-json/183807/2 "2010-02-20T20:00:47Z")

</div>

Hi Camille,

On Sat, 2010-02-20 at 17:15 +0100, Camille R. wrote:

> Hello,
> 
> I’m working on a Rails app which has a REST API. I manage two formats  
> JSON and XML.  
> Very often to simplify the use if the API, I’m making includes. But when  
> you add params to to\_json and to\_xml like :only, :except, it’s not only  
> applied on the root object but on all the objects included.

I use Builder when the to\_xml method is not flexible enough.

[http://api.rubyonrails.org/classes/Builder/XmlMarkup.html](http://api.rubyonrails.org/classes/Builder/XmlMarkup.html)

For json, there is no current equivalent AFAIK, but googling ‘rails  
builder json’ gave some trails to follow.

HTH,  
Bill
