| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
10年前发布

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

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

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1416360745273.html
JSON开发包 JsonMapper