jsonmapper下载 - php json解析器

1127 2020-03-04 PHP - 官方网站

php json解析器,将json字符串转换成php类或数组。


v1.6.0.zip(v1.6.0) 下载

v1.5.0.zip(v1.6.0) 下载

v1.5.2.zip(v1.6.0) 下载

v1.5.1.zip(v1.6.0) 下载

v1.1.1.zip(v1.6.0) 下载

v1.4.0.zip(v1.6.0) 下载

v1.2.0.zip(v1.6.0) 下载

v1.3.0.zip(v1.6.0) 下载

v1.1.0.zip(v1.6.0) 下载

v1.0.0.zip(v1.6.0) 下载

v2.0.0.zip(v2.0.0) 下载



Basic usage

  1. Register an autoloader that can load PSR-0 compatible classes.

  2. Create a JsonMapper object instance

  3. Call the map or mapArray method, depending on your data

Map a normal object:

require 'autoload.php';
$mapper = new JsonMapper();
$contactObject = $mapper->map($jsonContact, new Contact());

Map an array of objects:

require 'autoload.php';
$mapper = new JsonMapper();
$contactsArray = $mapper->mapArray(
    $jsonContacts, array(), 'Contact'

Instead of array() you may also use ArrayObject and descending classes.


JSON from an address book web service:

    'name':'Sheldon Cooper',
    'address': {
        'street': '2311 N. Los Robles Avenue',
        'city': 'Pasadena'

Your local Contact class:

class Contact
     * Full name
     * @var string
    public $name;

     * @var Address
    public $address;

Your local Address class:

class Address
    public $street;
    public $city;

    public function getGeoCoords()
        //do something with $street and $city

Your application code:

$json = json_decode(file_get_contents('http://example.org/sheldon.json'));
$mapper = new JsonMapper();
$contact = $mapper->map($json, new Contact());

echo "Geo coordinates for " . $contact->name . ": "
    . var_export($contact->address->getGeoCoords(), true);

Property type mapping

JsonMapper uses several sources to detect the correct type of a property:

  1. The setter method (set + ucwords($propertyname)) is inspected.

    Underscores "_" and hyphens "-" make the next letter uppercase. Property foo_bar-baz leads to setter method setFooBarBaz.

    1. If it has a type hint in the method signature then its type used:

      public function setPerson(Contact $person) {...}
    2. The method's docblock is inspected for @param $type annotations:

       * @param Contact $person Main contact for this application
      public function setPerson($person) {...}
    3. If no type could be detected, the plain JSON value is passed to the setter method.

  2. @var $type docblock annotation of class properties:

     * @var \my\application\model\Contact
    public $person;

    The property has to be public to be used directly. Protected and private properties cannot be set; you will have to provide a setter method for them.

    If no type could be detected, the property gets the plain JSON value set.

    If a property can not be found, JsonMapper tries to find the property in a case-insensitive manner. A JSON property isempty would then be mapped to a PHP propertyisEmpty.

Supported type names

  • Simple types

    • string

    • bool, boolean

    • int, integer

    • double, float

    • array

    • object

  • Class names, with and without namespaces

    • Contact - exception will be thrown if the JSON value is null

  • Arrays of simple types and class names:

    • int[]

    • Contact[]

  • Multidimensional arrays:

    • int[][]

    • TreeDeePixel[][][]

  • ArrayObjects of simple types and class names:

    • ContactList[Contact]

    • NumberList[int]

  • Nullable types:

    • int|null - will be null if the value in JSON isnull, otherwise it will be an integer

    • Contact|null - will be null if the value in JSON isnull, otherwise it will be an object of type Contact

ArrayObjects and extending classes are treated as arrays.

Variables without a type or with type mixed will get the JSON value set directly without any conversion.

See phpdoc's type documentation for more information.

Simple type mapping

When an object shall be created but the JSON contains a simple type only (e.g. string, float, boolean), this value is passed to the classes' constructor. Example:

PHP code:

 * @var DateTime
public $date;



This will result in new DateTime('2014-05-15') being called.

Class map

When variables are defined as objects of abstract classes or interfaces, JsonMapper would normally try to instantiate those directly and crash.

Using JsonMapper's $classMap property, you can specify which classes shall get instantiated instead:

$jm = new JsonMapper();
$jm->classMap['Foo'] = 'Bar';

This would create objects of type Bar when a variable is defined to be of type Foo.

It is also possible to use a callable in case the actual implementation class needs to be determined dynamically (for example in case of a union). The mapped class ('Foo' in the example below) and the Json data are passed as parameters into the call.

$mapper = function ($class, $jvalue) {
    // examine $class and $jvalue to figure out what class to use...
    return 'DateTime';

$jm = new JsonMapper();
$jm->classMap['Foo'] = $mapper;


JsonMapper throws an exception when a JSON property is null, unless the PHP class property has a nullable type - e.g. Contact|null.

If your API contains many fields that may be null and you do not want to make all your type definitions nullable, set:

$jm->bStrictNullTypes = false;


JsonMapper's setLogger() method supports all PSR-3 compatible logger instances.

Events that get logged:

  • JSON data contain a key, but the class does not have a property or setter method for it.

  • Neither setter nor property can be set from outside because they are protected or private

Handling invalid or missing data

During development, APIs often change. To get notified about such changes, JsonMapper can be configured to throw exceptions in case of either missing or yet unknown data.

Unknown properties

When JsonMapper sees properties in the JSON data that are not defined in the PHP class, you can let it throw an exception by setting $bExceptionOnUndefinedProperty:

$jm = new JsonMapper();
$jm->bExceptionOnUndefinedProperty = true;

You may also choose to handle those properties yourself by setting a callable to $undefinedPropertyHandler:

 * Handle undefined properties during JsonMapper::map()
 * @param object $object    Object that is being filled
 * @param string $propName  Name of the unknown JSON property
 * @param mixed  $jsonValue JSON value of the property
 * @return void
function setUndefinedProperty($object, $propName, $jsonValue)
    $object->{'UNDEF' . $propName} = $jsonValue;

$jm = new JsonMapper();
$jm->undefinedPropertyHandler = 'setUndefinedProperty';

Missing properties

Properties in your PHP classes can be marked as "required" by putting @required in their docblock:

 * @var string
 * @required
public $someDatum;

When the JSON data do not contain this property, JsonMapper will throw an exception when $bExceptionOnMissingData is activated:

$jm = new JsonMapper();
$jm->bExceptionOnMissingData = true;

Option $bRemoveUndefinedAttributes causes JsonMapper to remove properties from the final object if they have not been in the JSON data:

$jm = new JsonMapper();
$jm->bRemoveUndefinedAttributes = true;

Private properties and functions

You can allow mapping to private and protected properties and setter methods by setting $bIgnoreVisibility to true:

$jm = new JsonMapper();
$jm->bIgnoreVisibility = true;

Simple types instead of objects

When a variable's type is a class and JSON data is a simple type like string, JsonMapper passes this value to the class' constructor.

If you do not want this, set $bStrictObjectTypeChecking to true:

$jm = new JsonMapper();
$jm->bStrictObjectTypeChecking = true;

An exception is then thrown in such cases.

Passing arrays to map()

You may wish to pass array data into map() that you got by calling

json_decode($jsonString, true)

By default, JsonMapper will throw an exception because map() requires an object as first parameter. You can circumvent that by setting $bEnforceMapType to false:

$jm = new JsonMapper();
$jm->bEnforceMapType = false;


Via Composer from Packagist:

$ composer require netresearch/jsonmapper

Related software

About JsonMapper


JsonMapper is licensed under the OSL 3.0.

Coding style

JsonMapper follows the PEAR Coding Standards.


Christian Weiske, cweiske.de