如何在json中获取西里尔字母符号?

huangapple go评论54阅读模式
英文:

How to get cyrillic symbols in json?

问题

I use CIRCULAR_REFERENCE_HANDLER to avoid circular references.

$items = $this->entityManager->getRepository(OrderMainCategory::class)->findAll();
$encoder = new JsonEncoder();
$defaultContext = [
    AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object) {
        return $object->getName();
    },
];
$normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext);
$serializer = new Serializer([$normalizer], [$encoder]);
$data = $serializer->serialize($items, 'json');
return $this->json($data);

but get {"id":1,"name":"\u0410\u043b\u043...

I know about JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES but i don't understand how to use it in this case

英文:

I use CIRCULAR_REFERENCE_HANDLER to avoid circular references.

        $items = $this->entityManager->getRepository(OrderMainCategory::class)->findAll();
        $encoder = new JsonEncoder();
        $defaultContext = [
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object) {
                return $object->getName();
            },
        ];
        $normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext);
        $serializer = new Serializer([$normalizer], [$encoder]);
        $data = $serializer->serialize($items, 'json');
        return $this->json($data);

but get {\u0022id\u0022:1,\u0022name\u0022:\u0022\\u0410\\u043b\\u043...

I know about JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES but i don't understand how to use it in this case

答案1

得分: 1

You can apply changes like this:

return $this->json(json_decode($data))
            ->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

因为在序列化之后,$data 是一个字符串。而 [AbstractController use][1]json() 方法默认只使用 JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT

英文:

You can apply changes like this:

return $this->json(json_decode($data))
            ->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Because after serialization the $data is a string. And json() method of AbstractController use only JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT by default.

huangapple
  • 本文由 发表于 2023年4月6日 20:37:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定