Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

best way to add root to json? #250

Closed
dadamssg opened this issue Mar 11, 2014 · 4 comments
Closed

best way to add root to json? #250

dadamssg opened this issue Mar 11, 2014 · 4 comments

Comments

@dadamssg
Copy link

I see there is an XmlRoot option for xml, what's the easiest way to do this for json?

Rather than this

{
    "id": 12,
    "name": "Billy Bob"
}

I'd like to get

{
    "user": {
        "id": 12,
        "name": "Billy Bob"
    }
}

The only way i can think to accomplish this is to json_decode it, add it to a stdClass and then json_encode it back again:

<?php
    $json = json_decode($this->get('jms_serializer')->serialize($user, 'json'));
    $obj = new \stdClass;
    $obj->user = $json;
    $json = json_encode($obj);

There's got to be an easier way.

@henrikbjorn
Copy link

Create a wrapper that is then serialized.

@dadamssg
Copy link
Author

then i would have to create wrapper classes for each object i would want to return.

@stof
Copy link
Contributor

stof commented Mar 16, 2014

$json = $this->get('jms_serializer')->serialize(array('user' => $user), 'json');

@Actine
Copy link

Actine commented Apr 21, 2014

+1. It would be great if the root element for JSON could be declared via annotation. There's little charm to do this explicitly with every response.
The problem I'm concerned about is a JSON Array hack.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants