1

I'm having trouble return the correct json from a controller action.

Right now, I'm using jms serializer to serialize an entity. Like so:

$serializedJobOrders = $serializer->serialize($jobOrders, 'json');

So I have a string of json that I would like to return. It's actually a json array of objects: [{},{},{}]

Before, I've just used the setContent() method on a response to return json. Like this:

$jsonResponse = new JsonResponse();
return $jsonResponse->setContent($serializer->serialize($jobOrders, 'json'));

However, there is a security issue with return a json array. It should be an object with an array in it. Something like {data: [{},{},{}]}. This is where I'm having the trouble though.

I can't just do:

return new JsonResponse(array('data' => $serializedJobOrders));

because that just creates an escaped string for the 'data' property. I would then have to parse it client-side. I don't think that would be the proper way to do it. To illustrate a bit, this is kind of what it looks like:

{data: "[{\u0022name\u0022: \u0022John\u0022},{\u0022name\u0022: \u0022John\u0022}]"}

How can I return the correct json? So that it looks like this:

{data: [
  {'name': 'john'},
  {'name': 'john'},
  {'name': 'john'}
]}

1 Answer 1

1

I don't know why but it hit me right after that I could just do something like:

$data = array('data' => $jobOrders);
$serializedJobOrders = $serializer->serialize($data, 'json');
// then just use the setContent() method again
return $jsonResponse->setContent($serializedJobOrders);

I truly don't know why it just hit after I spent the time asking this question, doh :)

I am wondering if it is unsafe to use the setContent() method like that though. Seems like it's kind of "raw".

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe the FOSRestBundle could be helpful for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.