將嵌套的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;
}
?></pre>
Your local Address class:
<?php
class Address
{
public $street;
public $city;
public function getGeoCoords()
{
//do something with the $street and $city
}
}
?></pre>
Your application code:
<?php
$json = json_decode(file_get_contents('
echo "Geo coordinates for " . $contact->name . ": "
. var_export($contact->address->getGeoCoords(), true);
?></pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!