I create a views with REST export
display, result are serialized with Json
,
In my formBuild method I want to parse JSON and Convert it to array and use it in select option
$host = \Drupal::request()->getHost();
$response = \Drupal::httpClient()
->get($host.'/get/slider' );
$json_string = $response->getBody()->getContents();
kint($json_string);
I see Symfony serialize class and find Deserialize
method with this example
$person = $serializer->deserialize($data, 'Acme\Person', 'xml');
According to this,I guess maybe I should something like
$results = $serializer->deserialize($json_string, '???', 'josn');
but what I should write in second param(???)? I try
$serialize = new Serializer\Serializer();
$json_string = $response->getBody()->getContents();
$entity = $serialize->deserialize($json_string, '\Drupal\node\Entity\Node::class', 'json') ;
but face me with error Symfony\Component\Serializer\Exception\UnexpectedValueException: Deserialization for the format json is not supported in Symfony\Component\Serializer\Serializer->deserialize()
.
And if you have better solution tell me How Can I deserilized views REST results?
update Also,I tried
$json_string = $response->getBody()->getContents();
$serializer = \Drupal::service('serializer');
$deserialized = $serializer->deserialize($json_string, \Drupal\node\Entity\Node::class, 'json');
but Symfony\Component\Serializer\Exception\UnexpectedValueException: A string must be provided as a bundle value. in Drupal\serialization\Normalizer\EntityNormalizer->denormalize()
'\Drupal\node\Entity\Node::class'
isn't right...that would either be'\Drupal\node\Entity\Node'
or\Drupal\node\Entity\Node::class
(no quotes). The latter being preferredjson_decode
.Json::decode
which is in D8), but that will leave you with an associative array like it would in D7. The idea of the serializer is to map the json straight back onto a classed object which is much better to work with