Posting JSON objects to Symfony 2
If you want to retrieve data in your controller that's been sent as standard JSON in the request body, you can do something similar to the following:
public function yourAction()
{
$params = array();
$content = $this->get("request")->getContent();
if (!empty($content))
{
$params = json_decode($content, true); // 2nd param to get as array
}
}
Now $params
will be an array full of your JSON data. Remove the true
parameter value in the json_decode()
call to get a stdClass
object.
How can I send JSON response in symfony2 controller
Symfony 2.1
$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');
return $response;
Symfony 2.2 and higher
You have special JsonResponse class, which serialises array to JSON:
return new JsonResponse(array('name' => $name));
But if your problem is How to serialize entity then you should have a look at JMSSerializerBundle
Assuming that you have it installed, you'll have simply to do
$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');
return new Response($serializedEntity);
You should also check for similar problems on StackOverflow:
- How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?
- Symfony 2 Doctrine export to JSON
Send Nested Json to a Symfony Form
hello i think the issue is on responses. try using CollectionType. In this exemple using ChoiceType for each object in your collection. See here: https://symfony.com/doc/current/reference/forms/types/collection.html#entry-options
->add('responses', CollectionType::class, [
'entry_type' => ChoiceType::class,
'entry_options' => [
'choices' => [
'1' => 'D',
'2' => 'A',
],
],
]);
Symfony 2 - Creating and persisting json-Object from Form Data. Use Entities and FormTypes?
If you are using doctrine have a look at simple array or array types.
Maps and converts array data based on PHP serialization. If you need to store an exact representation of your array data, you should consider using this type as it uses serialization to represent an exact copy of your array as string in the database. Values retrieved from the database are always converted to PHP’s array type using deserialization or null if no data is present.
The annotation for that is:
/**
* @var YourType[]
* @ORM\Column(type="array")
*/
Send POST Data with Ajax, withtout form, to a Symfony2 Controller, in JSON format
I found the solution.
It's not really difficult.
It is not necessary to JSonify data. The controller has the capability to understand the original datatype.
So here is my simplified AJAX call:
function validerSession()
{
obj = new Object();
obj["title"] = "Title for example";
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: obj,
success: function (donnees) {
data = Parse.JSON(donnees);
alert(data.title); //Show "Title for example"
}
});
}
And here is my Controller. It can recover data as an array of values.
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = $request->request->all();
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data["title"], 'json');
return new Response($response);
}
Thanks for the help!
Symfony post request body parameters?
That is the expected behavior. You are sendind a JSON string inside the body of the request.
In this case, you need json_decode to convert the JSON string into an array or object, in order to access the data.
$parameters = json_decode($request->getContent(), true);
echo $parameters['name']; // will print 'user'
How to pass JSON data to rest API in symfony2
FOSRestBundle was created for these purposes. And I think you should start to use it in your project. It has no overhead and is easy to use.
https://github.com/FriendsOfSymfony/FOSRestBundle
Regards.
Related Topics
Retrieve All Hashtags from a Tweet in a PHP Function
Requires Ext-Fileinfo. How to Add That into My Composer.JSON File
Parse Xml Namespaces with PHP Simplexml
How to Easily Consume a Web Service from PHP
Converting Object to JSON and JSON to Object in PHP, (Library Like Gson for Java)
How to Use Regexiterator in PHP
How to Setup Table Prefix in Symfony2
Getting Time Difference Between Two Times in PHP
How to Remove Square Brackets and Anything Between Them with a Regex
Get a PHP Object Property That Is a Number
How to Use Cookies Across Two Different Domains
Create a Comma-Separated String from a Single Column of an Array of Objects
Will Copy-On-Write Prevent Data Duplication on Arrays
Getting a Modified Preorder Tree Traversal Model (Nested Set) into a <Ul>