2

I'm working on REST APIs with Symfony but my json_decode function returns null with my array. I've seen that he can be a probleme with encoding but i'm not sure. Here's my json :

{
    "id": 1,
    "title": "Titre",
    "content": "Contenu",
    "vendeur": null
}

Here's my functions to serialize and decode json :

/**
 * @Route("/api_articles_list", name="api_articles_list")
 * @Method({"GET"})
 */

public function showActionListSerialize()

{

    $articles =   $this->getDoctrine()->getRepository('AppBundle:Article')->findAll();

   // return new JsonResponse(array('articles' => $articles));

    $data =  $this->get('serializer')->serialize($articles, 'json');

    $response = new Response($data);

    $response->headers->set('Content-Type', 'application/json');


    return $response;



}

/**
 * @Route("/api_articles_list/articles_list", name="articles_list")
 * @Method({"GET"})
 */
public function showActionList()

{

    $articles = json_decode(utf8_encode($this->showActionListSerialize()), true);

    var_dump($articles);
    return $this->render('listeArticles.html.twig', array('articles' => $articles));

}
2
  • what does $articles return in showActionListSerialize ? I think you'll need to write it like this $this->getDoctrine()->getManager()->getRepository('AppBundle:Article')->findAll() Commented Nov 25, 2018 at 22:10
  • Please provide a minimal reproducible example. Also, you don't decode arrays, you might want to clarify that in your question. That said, as a new user, please take the tour and read How to Ask. Commented Nov 26, 2018 at 9:30

2 Answers 2

1

You are trying to encode an array, put the encode function after serializing the list:

/**
 * @Route("/api_articles_list", name="api_articles_list")
 * @Method({"GET"})
 */

public function showActionListSerialize()

{

    $articles =   $this->getDoctrine()->getRepository('AppBundle:Article')->findAll();

   // return new JsonResponse(array('articles' => $articles));

    $data =  $this->get('serializer')->serialize($articles, 'json');

    $response = new Response(utf8_encode($data));

    $response->headers->set('Content-Type', 'application/json');


    return $response;



}

/**
 * @Route("/api_articles_list/articles_list", name="articles_list")
 * @Method({"GET"})
 */
public function showActionList()

{

    $articles = json_decode($this->showActionListSerialize(), true);

    var_dump($articles);
    return $this->render('listeArticles.html.twig', array('articles' => $articles));

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

3 Comments

Would you explain me why encoding the data after serializing the list? The findAll function return an array of object. In fact the symfony Serializer does 2 things when you call the serialize method. First, it performs a normalization to convert the data into a well formed array. It is a recursive action so the normalizer check the type of the data and chose the corresponding normalizer. As it is an array of Article objects, it will use ObjectNormalizer each time it finds an Article. Then after the normalization step is done, the Symfony serializer performs a json_encode.
I was talking about the "utf8_encode" function, this function acceptes only parameter of type "string", in your code, you return an object of type "Reponse" so the function "utf8_encode" will be applied to the object "response" not the serialized json.
Oh alright but actually that's not the reason why $articles variable is null
0

First of all Welcome to StackOverflow,

Your second controller should look like this in order to achieve your goal:

/**
 * @Route("/api_articles_list/articles_list", name="articles_list")
 * @Method({"GET"})
 */
public function showActionList()
{
    $articles = json_decode(utf8_encode($this->showActionListSerialize()->getContent()), true);

    var_dump($articles);

    return $this->render('listeArticles.html.twig', array('articles' => $articles));

}

First using utf8_encode is not mandatory. Then your method showActionListSerialize returns a HttpFoundation Response object.

When you instanciated the response with the serialized data like this:

$response = new Response($data);

in fact it is the same as doing:

$response->setContent($data);

So to access the JSON data you need the getContent method.

The actual output of

var_dump(utf8_encode($this->showActionListSerialize());

is :

HTTP/1.0 200 OK Cache-Control: no-cache, private Content-Type: application/json Date: Mon, 26 Nov 2018 13:25:22 GMT [{"content":"Lorem ipsum","vendeur":"test_vendeur","id":1,"title":"title_test"}]"

and the output of

var_dump(utf8_encode($this->showActionListSerialize()->getContent());

is

[{"content":"Lorem ipsum","vendeur":"test_vendeur","id":1,"title":"title_test"}]

This solution should work for you. And your twig template should looks like:

{% block body %}
    {% for article in articles %}
        <br>
        id: {{ article.id }} <br>
        title: {{ article.title }}<br>
        content: {{ article.content }}<br>
        vendeur: {{ article.vendeur }}
    {% endfor %}
{% endblock %}

1 Comment

You're welcome. Anyway, don't forget to mark this answer as beeing the solution of your issue if it really solved it.

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.