Symfony 4:在JSON响应中未转义斜线

时间:2019-05-09 09:46:28

标签: php json symfony symfony4

早上好,

我的symfony 4 Api有问题。

我应该返回一个json响应,但是序列化程序返回带斜杠的字符串。我不知道如何逃脱。

在我的控制器下面:


use App\Entity\Category;
use App\Form\CategoryType;
use App\Repository\CategoryRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface as SerializerInterfaceAlias;
use FOS\RestBundle\Controller\Annotations as Rest;

/**
 * Category Controller
 * @Route("/api", name="api_")
 */
class CategoryController extends AbstractController
{
    /**
     * @Rest\Get("/categories")
     * @param CategoryRepository $categoryRepository
     * @param SerializerInterfaceAlias $serializer
     */
    public function index(CategoryRepository $categoryRepository, SerializerInterfaceAlias $serializer)
    {
        $jsonContent = $serializer->serialize($categoryRepository->findall(), 'json', ['json_encode_options' => JSON_UNESCAPED_SLASHES]);
        return $jsonContent;
    }
[....]
}

我的回报就像:

"[{\"id\":3,\"name\":\"toto\",\"logo\":\"tata\",\"description\":\"lolo\",\"dateCreated\":\"2019-05-09T10:30:39+00:00\"},{\"id\":4,\"name\":\"tata\",\"logo\":\"titi\",\"description\":\"tutu\",\"dateCreated\":\"2019-05-09T10:30:49+00:00\"}]"

有关信息,我使用 PHP 7.1 Symfony 4.2

所以我想要一个正确的json格式...不带斜线:(

您有什么建议吗? :)

谢谢!

1 个答案:

答案 0 :(得分:1)

我最终解决了#RubberDuckDebugging

我不需要在这里使用序列化器。

我只需要返回:

case ON_VISITOR_RECORD_UPDATED:
     console.log(JSON.stringify(state.get("visitorRecords")));
     const updatedRecords = state.visitorRecords.map(record => {
         if (record.id === action.bookingBeingUpdated) {
             return new Map({
                 ...record,
                 expectedArrival: action.updatedExpectedArrival
                 // other fields...
             });
         }
         return record;
     });
return state.merge({
    state,
    fromJS({visitorRecords: updatedRecords})
});

那很简单。抱歉:)