Unravel various models in PHP Symfony by decoding JSON data into objects

Is there a way to effectively convert a multidimensional JSON into an object or model?

When attempting to convert a JSON with nested structures, only the outer layer is successfully converted while inner layers remain as arrays. How can this issue be resolved?

Below are the models:

<?php
namespace AppBundle;

class Company {
    /**
     * @var string
     */
    protected $companyName = '';

    /**
     * @return string
     */
    public function getCompanyName()
    {
        return $this->companyName;
    }

    /**
     * @param string $companyName
     * @return void
     */
    public function setCompanyName($companyName)
    {
        $this->companyName = $companyName;
    }
}

class User {
    /**
     * @var \AppBundle\Company
     */
    protected $company = null;

    /**
     * @var string
     */
    protected $username = '';

    /**
     * @return \AppBundle\Company
     */
    public function getCompany() {
        return $this->company;
    }

    /**
     * @param \AppBundle\Company $company
     * @return void
     */
    public function setCompany($company) {
        $this->company = $company;
    }

    /**
     * @return string
     */
    public function getUsername() {
        return $this->username;
    }

    /**
     * @param string $username
     * @return void
     */
    public function setUsername($username) {
        $this->username = $username;
    }
}
?>

Instructions on converting JSON to model:

<?php
namespace AppBundle\Controller;

class DefaultController extends \Symfony\Bundle\FrameworkBundle\Controller\Controller
{

    public function indexAction()
    {
        // Initialize serializer
        $objectNormalizer = new \Symfony\Component\Serializer\Normalizer\ObjectNormalizer();
        $jsonEncoder = new \Symfony\Component\Serializer\Encoder\JsonEncoder();
        $serializer = new \Symfony\Component\Serializer\Serializer([$objectNormalizer], [$jsonEncoder]);

        // Set up test model
        $company = new \AppBundle\Company();
        $company->setCompanyName('MyCompany');
        $user = new \AppBundle\User();
        $user->setCompany($company);
        $user->setUsername('MyUsername');

        // Serialize test model to JSON
        $json = $serializer->serialize($user, 'json');
        dump($user); // Model is correct, Company is an instance of \AppBundle\Company
        dump($json); // JSON is valid

        // Deserialize JSON to model
        $user = $serializer->deserialize($json, \AppBundle\User::class, 'json');
        dump($user); // Issue: Company is now an array instead of an instance of \AppBundle\Company

        // Denormalize JSON to model
        $userArray = $serializer->decode($json, 'json');
        $user = $serializer->denormalize($userArray, \AppBundle\User::class);
        dump($user); // Problem: Company is still an array instead of an instance of \AppBundle\Company
    }
}
?>

Answer №1

The issue has been successfully resolved.

One important aspect to consider is the requirement of PHP 7 and the usage of annotations, which I have not yet experimented with.

It is crucial to ensure that the variable is properly set in the setCompany() function.

public function setCompany(Company $company) {
    $this->company = $company;
}

Additionally, the ReflectionExtractor() must be implemented.

use Symfony\Component\Serializer\Normalizer;
use Symfony\Component\PropertyInfo\Extractor;
$objectNormalizer = new ObjectNormalizer(
    null,
    null,
    null,
    new ReflectionExtractor()
);

Only the deserialize() method is required as it encapsulates both decode() and denormalize().

http://symfony.com/doc/current/components/serializer.html

Below is the corrected code:

Company class:

class Company {
    /**
     * @var string
     */
    protected $companyName = '';

    /**
     * @return string
     */
    public function getCompanyName() {
        return $this->companyName;
    }

    /**
     * @param string $companyName
     * @return void
     */
    public function setCompanyName($companyName) {
        $this->companyName = $companyName;
    }
}

User class:

class User {
    /**
     * @var \AppBundle\Company
     */
    protected $company = null;

    /**
     * @var string
     */
    protected $username = '';

    /**
     * @return \AppBundle\Company
     */
    public function getCompany() {
        return $this->company;
    }

    /**
     * @param \AppBundle\Company $company
     * @return void
     */
    public function setCompany(Company $company) {
        $this->company = $company;
    }

    /**
     * @return string
     */
    public function getUsername() {
        return $this->username;
    }

    /**
     * @param string $username
     * @return void
     */
    public function setUsername($username) {
        $this->username = $username;
    }
}
?>

Controller class:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\Serializer\Normalizer;
use Symfony\Component\PropertyInfo\Extractor;
use Symfony\Component\Serializer;

class DefaultController extends Controller {
    public function indexAction() {
        $objectNormalizer = new ObjectNormalizer(
            null,
            null,
            null,
            new ReflectionExtractor()
        );
        $jsonEncoder = new JsonEncoder();
        $serializer = new Serializer([$objectNormalizer], [$jsonEncoder]);

        $company = new \AppBundle\Company();
        $company->setCompanyName('MyCompany');

        $user = new \AppBundle\User();
        $user->setCompany($company);
        $user->setUsername('MyUsername');

        $json = $serializer->serialize($user, 'json');
        dump($user, $json);

        $user2 = $serializer->deserialize($json, \AppBundle\User::class, 'json');
        dump($user2);
    }
}
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the Error for the deprecated Class in Firestore SDK for PHP?

I recently updated to a newer version of 'google/cloud-firestore' and encountered an error. Here is the specific error message: Google\Cloud\Firestore\V1beta1\StructuredQuery_CollectionSelector is deprecated and will be ...

Mistakes in PHP countdown clock

I've been working on a PHP countdown clock for my website, but I'm running into some issues. The clock is going to be displayed on the site, but when it shows 1 minute remaining, it still displays "1 Minutes" with an extra S. Additionally, it als ...

Why isn't my custom wildcard search working properly in Marklogic using the Java API?

I am attempting to perform a wildcarded search in Marklogic using Java. Here is the current data structure in Marklogic: /articles/1.json 1.json: [{ "title":"hello%20world1", "content":"article content etc..." }] /articles/2.json 2.json: [{ "title ...

Using PHP to send variables to an AJAX function via parameters

I've encountered an issue while attempting to pass 4 variables through the parameters of the ajax function. The variables I'm trying to pass include the URL, action, ID, and timeout in milliseconds. Unfortunately, the function is not accepting th ...

Process for evaluating information before storing in database: MongoDB

The concept behind the application is to display all "E-number" ingredients found in a product (such as E100 and E200). Let's consider a scenario where we have a variety of products being added to our database (via JSONs, web scraping, or APIs). Each ...

Converting a JSONObject to a JSONArray on Android is not possible

My android code below is producing an error: org.json.JSONException: Value {"ID":1,"DisplayName":"Manish","UserName":"[email protected]"} at AuthenticateUserResult of type org.json.JSONObject cannot be converted to JSONArray The code snippet is a ...

searching for a document in mongodb that matches a particular id and username

{ "data": [ { "_id": 555, "username": "jackson", "status": "i am coding", "comments": [ { "user": "bob", "comment": "bob me " }, { ...

What is the best way to use jQuery to fill a dropdown menu with options from a JSON object?

Looking to populate a dropdown box #dropdown with values from a json object stored in a JavaScript string variable. How can I access each element as value/label pairs and insert them into the dropdown? The structure of the json string is as follows: [{"n ...

Creating a Timeout Function for Mobile Browsers in JavaScript/PHP

Currently, I am developing a mobile-based web application that heavily relies on AJAX and Javascript. The process involves users logging in through a login page, sending the data via post to the main page where it undergoes a mySQL query for validation. If ...

PHP concealing certain details in the link path

Could I change the link for my website to direct to the index page to instead link to the "AboutUs Page" like rather than using ...

Creating form inputs dynamically in HTML and then sending them to a PHP script programmatically

On my webpage, users can click a button to add new form inputs as needed. However, I'm running into an issue trying to access these new inputs in the PHP file where I submit the data. Here is the code snippet for the button within the form on the pag ...

Translation of country codes into the complete names of countries

Currently, my code is utilizing the ipinfo.io library to retrieve the user's country information successfully. This is the snippet of code I am using to fetch the data: $.get("https://ipinfo.io?token=0000000000", function(response) { console.log ...

Tips for optimizing fasterxml ObjectMapper for use with codehaus annotations

I am utilizing the ObjectMapper class within the fasterxml package (com.fasterxml.jackson.databind.ObjectMapper) to serialize certain POJOs. The issue I am encountering is that all the annotations in the POJOs belong to the outdated codehaus library. The ...

Serializing an array into JSON format as I input more data

I am currently working on a form that allows me to input data about individual items. My goal is to add each submitted item to a JSON array, which will be stored in a file. Below is the code I am using: for (Item obj : list) { out.print(obj.getId()) ...

Issue when attempting to post to Facebook Page using PHP script as Page identity

Currently, I have implemented the following PHP code to successfully post on my page wall as an admin. However, I am looking to post on the wall using the actual page name or page ID instead of as an individual admin. Is there a way to achieve this? I at ...

Utilizing Ajax and JQuery to invoke a PHP function with parameters

Seeking to implement a record deletion feature using JQuery/Ajax in order to avoid the need for page reload every time a delete action is performed. I have a Movie.php file which acts as a model object for Movie and contains a function called delete_movie ...

SSL certificate error in authorize.net payment gateway encountered

Currently, I am working on integrating the authorize payment gateway in PHP. To accomplish this task, I referred to the PHP Integration Guide. Furthermore, I downloaded the necessary resources from Php-SDK Example. However, upon execution, an error occur ...

Issue with installing PHPixie framework using php -r command

Let me start by saying that I am completely new to PHP and am currently following a tutorial on PHPixie download instructions found here: PHPixie download instructions I should also note that I am attempting to install this on my web host. Here are the i ...

What is the reason behind Jackson's decision to change a byte array into a base64 string when converting it to JSON

When dealing with a byte array in a DTO and converting it to JSON using Jackson's ObjectMapper, the byte array is automatically converted into a base64 string. This can be seen in the example below. @Data @AllArgsConstructor class TestDTO { privat ...

issues with comparison of csv strings

After thoroughly examining the array filled with data from fgetcsv(), I noticed that a specific string is present in the content but surprisingly, when using in_array(), it returns false function checkFieldCSV($index,$code){ $codes = array(); if ...