Arrays Symfony 5-如何在JSON中操作序列化对象

Arrays Symfony 5-如何在JSON中操作序列化对象,arrays,json,symfony,Arrays,Json,Symfony,我想序列化一个对象以获取JSON。序列化此对象时,会得到以下结果: { "id": 1, "title": "Title", "authors": [ "/api/authors/1", "/api/authors/2" ] } 我想更改JSON中的“Authors”数据,并向其传递一个数组。像这个例子: {

我想序列化一个对象以获取JSON。序列化此对象时,会得到以下结果:

{
    "id": 1,
    "title": "Title",
    "authors": [
        "/api/authors/1",
        "/api/authors/2"
    ]
}
我想更改JSON中的“Authors”数据,并向其传递一个数组。像这个例子:

{
    "id": 1,
    "title": "Title",
    "authors": [
        "id":1,
        "name": "Robert Smith",
        "booksCount":1
        etc etc....
    ]
} 
这是我的代码

   $book = $bookRepository->find($id);
    
    
    $authors = array("authors" => $bookRepository->find($id)->getAuthors());

    return $this->json($book, 200, []);
我将用$authors中的数组替换“author”JSON值。
如何操作我想要的JSON格式?

一种可能是使用JSON\u decode函数

PHP文档:,

或来自JMS的@VirtualProperty()注释

/**
*@Serializer\VirtualProperty()
*/
公共函数getAuthorsCustom()
{
返回。。。;
}

一种可能性是使用json\u decode函数

PHP文档:,

或来自JMS的@VirtualProperty()注释

/**
*@Serializer\VirtualProperty()
*/
公共函数getAuthorsCustom()
{
返回。。。;
}

首先,在通往某条路线的路径上保留对作者的引用是很奇怪的
@Route(“/api/authors/{authord}”)

建议: <>我会考虑使用这样的ORM关系映射:

Book.php

/**
 * @ORM\OneToMany(targetEntity="Author", mappedBy="book")
 */
private $authors;
/**
 * @ORM\ManyToOne(targetEntity="Book", inversedBy="authors")
 * @JoinColumn(name="book_id", referencedColumnName="id")
 */
private $book;
/**
 * @var $ids int[] array of author identifiers
*/
public function getAuthorsByIds(array $ids)
{
    // it should return array of author entities
    return $this->createQueryBuilder('author')
        ->select('author')
        ->where("author.id IN (?)")
        ->setParameter($ids)
        ->getQuery()
        ->getResult();
}
Author.php

/**
 * @ORM\OneToMany(targetEntity="Author", mappedBy="book")
 */
private $authors;
/**
 * @ORM\ManyToOne(targetEntity="Book", inversedBy="authors")
 * @JoinColumn(name="book_id", referencedColumnName="id")
 */
private $book;
/**
 * @var $ids int[] array of author identifiers
*/
public function getAuthorsByIds(array $ids)
{
    // it should return array of author entities
    return $this->createQueryBuilder('author')
        ->select('author')
        ->where("author.id IN (?)")
        ->setParameter($ids)
        ->getQuery()
        ->getResult();
}
然后为您服务:

$book = $entityManager->getRepository(App\Entity\Book::class)->find($id);

return $book;
然后在控制器中:

$book = $yourService->getBook($book_id);

return new JSONResponse($book);
然后在JavaScript中:

let bookJSON = JSON.parse(responseData);
let authors = bookJSON.authors;
解决方案: AuthorRepository.php

/**
 * @ORM\OneToMany(targetEntity="Author", mappedBy="book")
 */
private $authors;
/**
 * @ORM\ManyToOne(targetEntity="Book", inversedBy="authors")
 * @JoinColumn(name="book_id", referencedColumnName="id")
 */
private $book;
/**
 * @var $ids int[] array of author identifiers
*/
public function getAuthorsByIds(array $ids)
{
    // it should return array of author entities
    return $this->createQueryBuilder('author')
        ->select('author')
        ->where("author.id IN (?)")
        ->setParameter($ids)
        ->getQuery()
        ->getResult();
}
您的控制器

$book = $bookRepository->find($id);
$authorIdentificators = $book->getAuthors();

// convert routes to array of ids
array_walk($authorIdentificators, function(&$route) {
    $route = explode('/', $route)[3];
});

$authors = $authorRepository->getAuthorsByIds($authorIdentificators);

// notice that your $authors private property is now array of objects (not array of strings(routes))
$book->setAuthors($authors);

return new JSONResponse($book); // now book JSON should have array of authors
您可以使用这个慢循环来代替存储库方法

$authors = $book->getAuthors();

// convert routes to array of entity objects:
array_walk($authors, function(&$route) {
    $route = $authorRepository->find(explode('/', $route)[3]);
});

首先,在通往某条路线的道路上,你们总是引用作者,这很奇怪
@Route(“/api/authors/{authord}”)

建议: <>我会考虑使用这样的ORM关系映射:

Book.php

/**
 * @ORM\OneToMany(targetEntity="Author", mappedBy="book")
 */
private $authors;
/**
 * @ORM\ManyToOne(targetEntity="Book", inversedBy="authors")
 * @JoinColumn(name="book_id", referencedColumnName="id")
 */
private $book;
/**
 * @var $ids int[] array of author identifiers
*/
public function getAuthorsByIds(array $ids)
{
    // it should return array of author entities
    return $this->createQueryBuilder('author')
        ->select('author')
        ->where("author.id IN (?)")
        ->setParameter($ids)
        ->getQuery()
        ->getResult();
}
Author.php

/**
 * @ORM\OneToMany(targetEntity="Author", mappedBy="book")
 */
private $authors;
/**
 * @ORM\ManyToOne(targetEntity="Book", inversedBy="authors")
 * @JoinColumn(name="book_id", referencedColumnName="id")
 */
private $book;
/**
 * @var $ids int[] array of author identifiers
*/
public function getAuthorsByIds(array $ids)
{
    // it should return array of author entities
    return $this->createQueryBuilder('author')
        ->select('author')
        ->where("author.id IN (?)")
        ->setParameter($ids)
        ->getQuery()
        ->getResult();
}
然后为您服务:

$book = $entityManager->getRepository(App\Entity\Book::class)->find($id);

return $book;
然后在控制器中:

$book = $yourService->getBook($book_id);

return new JSONResponse($book);
然后在JavaScript中:

let bookJSON = JSON.parse(responseData);
let authors = bookJSON.authors;
解决方案: AuthorRepository.php

/**
 * @ORM\OneToMany(targetEntity="Author", mappedBy="book")
 */
private $authors;
/**
 * @ORM\ManyToOne(targetEntity="Book", inversedBy="authors")
 * @JoinColumn(name="book_id", referencedColumnName="id")
 */
private $book;
/**
 * @var $ids int[] array of author identifiers
*/
public function getAuthorsByIds(array $ids)
{
    // it should return array of author entities
    return $this->createQueryBuilder('author')
        ->select('author')
        ->where("author.id IN (?)")
        ->setParameter($ids)
        ->getQuery()
        ->getResult();
}
您的控制器

$book = $bookRepository->find($id);
$authorIdentificators = $book->getAuthors();

// convert routes to array of ids
array_walk($authorIdentificators, function(&$route) {
    $route = explode('/', $route)[3];
});

$authors = $authorRepository->getAuthorsByIds($authorIdentificators);

// notice that your $authors private property is now array of objects (not array of strings(routes))
$book->setAuthors($authors);

return new JSONResponse($book); // now book JSON should have array of authors
您可以使用这个慢循环来代替存储库方法

$authors = $book->getAuthors();

// convert routes to array of entity objects:
array_walk($authors, function(&$route) {
    $route = $authorRepository->find(explode('/', $route)[3]);
});

你现在有没有代码?对不起,这篇文章已经编辑了。你现在有没有代码?对不起,这篇文章已经编辑了。嗨!非常感谢你的帮助。我决定采用第二种解决方案,但出现了以下错误:“警告:explode()希望参数2是字符串,数组给定”。还有一个问题:为什么在函数中我们给出了两个参数($route和$key),但我们只使用$route?非常感谢。您的
$book->getAuthors()的结果是什么?我希望它是数组或字符串:[“/api/authors/1”、“/api/authors/2”]
$route
应该是
$AuthorityIdentificators
数组的每个元素,因此您有一个数组数组,但没有字符串数组。可能getAuthors()返回如下内容:['authors'=>[“/api/authors/1”,“/api/authors/2”]。我不知道,你让我知道:)
array\u walk
的回调可以有3个参数,每个参数都是可选的,所以第二个($key)在这里没有用处(谢谢,我会编辑它)。我检查它,然后$book->getAuthors()向我发送一个对象。你建议我做什么?我转换数组中的对象?我是这样进行的:我得到了作者,通过一个循环,我得到了$AuthorientIndicators的一个数组,但是,即使在取消调试(我确认该变量是数组)之后,我也得到了相同的错误消息“警告:explode()希望参数2是字符串,对象给定”好的,但是您必须向我展示您的
$authorIdentificators
变量是什么。它必须是一个字符串数组。嗨!非常感谢你的帮助。我决定采用第二种解决方案,但出现了以下错误:“警告:explode()希望参数2是字符串,数组给定”。还有一个问题:为什么在函数中我们给出了两个参数($route和$key),但我们只使用$route?非常感谢。您的
$book->getAuthors()的结果是什么?我希望它是数组或字符串:[“/api/authors/1”、“/api/authors/2”]
$route
应该是
$AuthorityIdentificators
数组的每个元素,因此您有一个数组数组,但没有字符串数组。可能getAuthors()返回如下内容:['authors'=>[“/api/authors/1”,“/api/authors/2”]。我不知道,你让我知道:)
array\u walk
的回调可以有3个参数,每个参数都是可选的,所以第二个($key)在这里没有用处(谢谢,我会编辑它)。我检查它,然后$book->getAuthors()向我发送一个对象。你建议我做什么?我转换数组中的对象?我是这样进行的:我得到了作者,通过一个循环,我得到了$AuthorientIndicators的一个数组,但是,即使在取消调试(我确认该变量是数组)之后,我也得到了相同的错误消息“警告:explode()希望参数2是字符串,对象给定”好的,但是您必须向我展示您的
$authorIdentificators
变量是什么。它必须是一个字符串数组。非常感谢!非常感谢你!