Php json decode to class

json_decode

Принимает закодированную в JSON строку и преобразует ее в переменную PHP.

Список параметров

json строка ( string ) для декодирования.

Эта функция работает только со строками в UTF-8 кодировке.

Замечание:

PHP реализует надмножество JSON, который описан в первоначальном » RFC 4627, — также кодируя и декодируя скалярные типы и NULL . RFC 4627 поддерживает эти значения только в случае, если они находятся внутри массива или объекта.

И хотя это надмножество согласуется с расширенным определением «JSON текста» из новых » RFC 7159 (который старается заменить собой RFC 4627) и » ECMA-404, это все равно может приводить к проблемам совместимости со старыми парсерами JSON, которые строго придерживаются RFC 4627 с кодированием скалярных значений.

Если TRUE , возвращаемые объекты будут преобразованы в ассоциативные массивы.

Указывает глубину рекурсии.

Битовая маска опций декодирования JSON. В настоящий момент поддерживается только JSON_BIGINT_AS_STRING (по умолчанию большие целые числа приводятся к числам с плавающей запятой (float))

Возвращаемые значения

Возвращает данные json преобразованные в соответствующие типы PHP. Значения true, false и null возвращаются как TRUE , FALSE и NULL соответственно. NULL также возвращается, если json не может быть преобразован или закодированные данные содержат вложенных уровней больше, чем допустимый предел для рекурсий.

Примеры

Пример #1 Пример использования json_decode()

var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , true ));

Результат выполнения данного примера:

object(stdClass)#1 (5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) > array(5) < ["a"] =>int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) >

Пример #2 Доступ к свойствам объектов с неправильными именами

Доступ к элементам объекта, которые содержат символы недопустимые согласно соглашению об именах PHP (т.е. дефис), может производиться путем обрамления имени элемента фигурными скобками и апострофами.

$obj = json_decode ( $json );
print $obj ->< 'foo-bar' >; // 12345

Пример #3 Распространенная ошибка при использовании json_decode()

// Следующие строки являются валидным кодом JavaScript, но не валидными JSON данными

// Имя и значение должны помещаться в двойные кавычки
// Одинарные кавычки использовать нельзя
$bad_json = «< 'bar': 'baz' >» ;
json_decode ( $bad_json ); // null

// Имя должно обрамляться в двойные кавычки
$bad_json = ‘< bar: "baz" >‘ ;
json_decode ( $bad_json ); // null

// Не должно быть завершающей запятой (без последующего элемента)
$bad_json = ‘< bar: "baz", >‘ ;
json_decode ( $bad_json ); // null

Пример #4 Ошибки с глубиной вложенных объектов ( depth )

// Создаем массив с ошибками.
$constants = get_defined_constants ( true );
$json_errors = array();
foreach ( $constants [ «json» ] as $name => $value ) if (! strncmp ( $name , «JSON_ERROR_» , 11 )) $json_errors [ $value ] = $name ;
>
>

Читайте также:  Java массивы array list

// Отображаем ошибки для разных глубин рекурсий
foreach ( range ( 4 , 3 , — 1 ) as $depth ) var_dump ( json_decode ( $json , true , $depth ));
echo ‘Last error: ‘ , $json_errors [ json_last_error ()], PHP_EOL , PHP_EOL ;
>
?>

Результат выполнения данного примера:

array(1) < [1]=>array(2) < ["English"]=>array(2) < [0]=>string(3) "One" [1]=> string(7) "January" > ["French"]=> array(2) < [0]=>string(3) "Une" [1]=> string(7) "Janvier" > > > Last error: JSON_ERROR_NONE NULL Last error: JSON_ERROR_DEPTH

Пример #5 json_decode() с большими целыми числами

var_dump ( json_decode ( $json ));
var_dump ( json_decode ( $json , false , 512 , JSON_BIGINT_AS_STRING ));

Результат выполнения данного примера:

object(stdClass)#1 (1) < ["number"]=>float(1.2345678901235E+19) > object(stdClass)#1 (1) < ["number"]=>string(20) "12345678901234567890" >

Примечания

Замечание:

Спецификация JSON не тоже самое, что и JavaScript, но является его частью.

Замечание:

В случае ошибки декодирования можно использовать json_last_error() для определения ее причины.

Список изменений

Версия Описание
5.6.0 Недопустимые варианты true, false и null не в нижнем регистре больше не допускаются во входящих данных, и приводят к предупреждениям.
5.4.0 Был добавлен параметр options .
5.3.0 Добавлен опциональный параметр depth . Глубина рекурсии по умолчанию увеличено с 128 до 512
5.2.3 Глубина рекурсии увеличена с 20 до 128
5.2.1 Добавлена поддержка декодирования основных типов JSON.

Смотрите также

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

JsonDecoder implementation that allows you to convert your JSON data into PHP class objects.

License

karriereat/json-decoder

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This package contains a JsonDecoder implementation that allows you to convert your JSON data into php class objects other than stdclass .

You can install the package via composer

composer require karriere/json-decoder 

By default the Decoder will iterate over all JSON fields defined and will try to set this values on the given class type instance. This change in behavior allows the use of json-decoder on classes that use the magic __get and __set functions like Laravel’s Eloquent models.

If a property equally named like the JSON field is found or a explicit Binding is defined for the JSON field it will be decoded into the defined place. Otherwise the property will just be created and assigned (you need the #[AllowDynamicProperties] attribute if you are on PHP 8.2.).

Читайте также:  Opera не загружает java

The JsonDecoder class can receive one parameter called shouldAutoCase . If set to true it will try to find the camel-case version from either snake-case or kebap-case automatically if no other binding was registered for the field and it will use an AliasBinding if one of the variants can be found.

Assume you have a class Person that looks like this:

#[AllowDynamicProperties] class Person < public int $id; public string $name; public ?string $lastname = ''; >

The following code will transform the given JSON data into an instance of Person .

$jsonDecoder = new JsonDecoder(); $jsonData = ''; $person = $jsonDecoder->decode($jsonData, Person::class);

Please be aware that since PHP 8.2. dynamic properties are deprecated. So if you still wish to have the ability to make use of those dynamic properties you have to add the PHP attribute AllowDynamicProperties to your class. If you are using PHP 8.2. (and greater) and don’t use the AllowDynamicProperties attribute all dynamic properties will be ignored.

Let’s extend the previous example with a property called address. This address field should contain an instance of Address . As of version 4 you can use the introduced method scanAndRegister to automatically generate the transformer based on class annotations. Since version 5 you can also make use of the property type instead of a class annotation.

class Person < public int $id; public string $name; /** * @var Address */ public $address; public ?Address $typedAddress = null; >

For this class definition we can decode JSON data as follows:

$jsonDecoder = new JsonDecoder(); $jsonDecoder->scanAndRegister(Person::class); $jsonData = ', , "typedAddress": >'; $person = $jsonDecoder->decode($jsonData, Person::class);

If you don’t use annotations or need a more flexible Transformer you can also create a custom transformer. Let’s look at the previous example without annotation.

class Person < public int $id; public string $name; public mixed $address; >

To be able to transform the address data into an Address class object you need to define a transformer for Person :

The transformer interface defines two methods:

  • register: here you register your field, array, alias and callback bindings
  • transforms: gives you the full qualified class name e.g.: Your\Namespace\Class
class PersonTransformer implements Transformer < public function register(ClassBindings $classBindings) < $classBindings->register(new FieldBinding('address', 'address', Address::class)); > public function transforms() < return Person::class; > >

After registering the transformer the JsonDecoder will use the defined transformer:

$jsonDecoder = new JsonDecoder(); $jsonDecoder->register(new PersonTransformer()); $jsonData = ''; $person = $jsonDecoder->decode($jsonData, Person::class);

Handling private and protected properties

As of version 4 the JsonDecoder class will handle private and protected properties out of the box.

Читайте также:  Introducing python билла любановича

Transforming an array of elements

If your JSON contains an array of elements at the root level you can use the decodeMultiple method to transform the JSON data into an array of class type objects.

$jsonDecoder = new JsonDecoder(); $jsonData = '[, ]'; $personArray = $jsonDecoder->decodeMultiple($jsonData, Person::class);

The following Binding implementations are available

Defines a JSON field to property binding for the given type.

new FieldBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);

This defines a field mapping for the property $property to a class instance of type $type with data in $jsonField .

Defines an array field binding for the given type.

new ArrayBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);

This defines a field mapping for the property $property to an array of class instance of type $type with data in $jsonField .

Defines a JSON field to property binding.

new AliasBinding(string $property, ?string $jsonField = null, bool $isRequired = false);

Defines a JSON field to property binding and converts the given string to a DateTime instance.

new DateTimeBinding(string $property, ?string $jsonField = null, bool $isRequired = false, $dateTimeFormat = DateTime::ATOM);

Defines a property binding that gets the callback result set as its value.

new CallbackBinding(string $property, private Closure $callback);

Apache License 2.0 Please see LICENSE for more information.

About

JsonDecoder implementation that allows you to convert your JSON data into PHP class objects.

Источник

json_decode to custom class

In PHP, you can use the json_decode() function to convert a JSON string into a PHP object or array. If you want to convert the JSON data into an instance of a custom class, you can use the second parameter of the json_decode() function, which specifies the class to use for the resulting object.

For example, if you have a JSON string like this:

And you have a custom class Person defined like this:

 class Person < public $name; public $age; public $email; >

You can create a new instance of the Person class and populate its properties using the values from the decoded JSON:

 $json = '[email protected]">'; class Person < public $name; public $age; public $email; > $person_array = json_decode($json, true); print_r($person_array);

Now you can use the $person variable as an instance of the Person class, with the properties name , age , and email set to the values from the JSON string.

 $json = '[email protected]">'; class Person < public $name; public $age; public $email; > $person_array = json_decode($json, true); $person = new Person(); $person->name = $person_array['name']; $person->age = $person_array['age']; $person->email = $person_array['email']; echo $person->name; // "John Doe" echo '-'; echo $person->age; // 30 echo '-'; echo $person->email; // "[email protected]"

Источник

Оцените статью