将嵌套的JSON结构映射成PHP类:JsonMapper

jopen 9年前

JsonMapper能够将嵌套的JSON结构映射成PHP类。从Web服务取得所需要的JSON数据,并将其转换成嵌套对象和数组 - 使用自己的模型类。

Map a normal object:

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

Map an array of objects:

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

JSON from a address book web service:

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

Your local Contact class:

<?php  class Contact  {      /**       * Full name       * @var string       */      public $name;        /**       * @var Address       */      public $address;  }  ?>

Your local Address class:

<?php  class Address  {      public $street;      public $city;        public function getGeoCoords()      {          //do something with the $street and $city      }  }  ?>

Your application code:

<?php  $json = json_decode(file_get_contents('http://example.org/bigbang.json'));  $mapper = new JsonMapper();  $contact = $mapper->map($json, new Contact());    echo "Geo coordinates for " . $contact->name . ": "      . var_export($contact->address->getGeoCoords(), true);  ?>

项目主页:http://www.open-open.com/lib/view/home/1416360745273