PHP Classes

File: doc/1_simple_mapping.md

Recommend this page to a friend!
  Classes of Julian Finkler   JSON Object Mapper   doc/1_simple_mapping.md   Download  
File: doc/1_simple_mapping.md
Role: Documentation
Content type: text/markdown
Description: Documentation
Class: JSON Object Mapper
Create objects of classes mapped from JSON strings
Author: By
Last change:
Date: 5 years ago
Size: 1,103 bytes
 

Contents

Class file image Download

Simple Data Mapping

? Go to index

If the json structure equals to your objects, the mapping is pretty easy. You only need to add the @JsonField-Annotation to the properties you wish to map, instantiate the mapper and call the mapDataToObject()-Method

For example you have a json file like this

{
    "firstname": "Pete",
    "surname": "Peterson",
    "age": 28,
    "height": 1.72,
    "is_cool": true,
    "nicknames": [
        "Pepe",
        "Pete"
    ]
}

And want to map the json to this object:

use MintWare\JOM\JsonField;

class SimplePerson
{
    / @JsonField */
    public $firstname;

    / @JsonField */
    public $surname;

    / @JsonField */
    public $age;

    / @JsonField */
    public $is_cool;

    / @JsonField */
    public $nicknames;
}

To map the JSON to the object you need to call the mapDataToObject()-method

$mapper = new MintWare\JOM\ObjectMapper();
$data = json_decode(file_get_contents('person.json'), true);
$person = $mapper->mapDataToObject($data, SimplePerson::class);

var_dump($person);