2012-03-25 15 views

risposta

65

Questo dovrebbe fare il trucco!

// convert object => json 
$json = json_encode($myObject); 

// convert json => object 
$obj = json_decode($json); 

Ecco un esempio

$foo = new StdClass(); 
$foo->hello = "world"; 
$foo->bar = "baz"; 

$json = json_encode($foo); 
echo $json; 
//=> {"hello":"world","bar":"baz"} 

print_r(json_decode($json)); 
// stdClass Object 
// (
// [hello] => world 
// [bar] => baz 
//) 

Se si desidera che l'uscita come un array invece di un oggetto, passare true a json_decode

print_r(json_decode($json, true)); 
// Array 
// (
// [hello] => world 
// [bar] => baz 
//)  

più su json_encode()

Vedi anche : json_decode()

+2

un problema ho a che fare con la società è - usando json_decode(), ottengo un oggetto stdClass, non il mio oggetto originale. Potrei usare serialize/unserialize, ma i miei oggetti cambiano struttura nel tempo anche se leggermente, rendendo la serializzazione inutilizzabile. – Dennis

+1

@Dennis 'unserialize' restituirà sempre un'istanza di' stdClass', questo non lo rende inutilizzabile. Si potrebbe facilmente progettare l'API per supportare qualcosa come '$ attrs = unserialize ($ json); $ person = new Person ($ attrs); 'Il tuo costruttore' Person' può quindi assegnare gli attributi di conseguenza. –

3
json_decode($json, true); 
// the second param being true will return associative array. This one is easy. 
12

per maggiore estendibilità per applicazioni su larga scala utilizzare lo stile oop con campi incapsulati.

modo semplice: -

class Fruit implements JsonSerializable { 

     private $type = 'Apple', $lastEaten = null; 

     public function __construct() { 
      $this->lastEaten = new DateTime(); 
     } 

     public function jsonSerialize() { 
      return [ 
       'category' => $this->type, 
       'EatenTime' => $this->lastEaten->format(DateTime::ISO8601) 
      ]; 
     } 
    } 

eco json_encode (nuova Fruit()); // che uscite:

{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"} 

reale GSON su PHP: -

  1. http://jmsyst.com/libs/serializer
  2. http://symfony.com/doc/current/components/serializer.html
  3. http://framework.zend.com/manual/current/en/modules/zend.serializer.html
  4. http://fractal.thephpleague.com/ - serializzare solo
+0

tutto ciò che accade solo invertire la funzione jsonSerialize .. –

+0

con l'uso di json il problema è la parte inversa perché jeson_decode restituisce solo un oggetto stdClass. Dovresti essere in grado di inizializzare un oggetto della tua classe fornendo una serie di valori di campo. Troppo in alto. basta usare la serializzazione semplice. – Hafenkranich

0

I ma de un metodo per risolvere questo. Il mio approccio è:

1 - Creare una classe astratta che abbia un metodo per convertire gli oggetti nell'array (incluso l'attr privato) usando Regex. 2 - Converte l'array restituito in json.

Io uso questa classe astratta come madre di tutte le mie classi di dominio codice

Classe:

namespace Project\core; 

abstract class AbstractEntity { 
    public function getAvoidedFields() { 
     return array(); 
    } 
    public function toArray() { 
     $temp = (array) $this; 

     $array = array(); 

     foreach ($temp as $k => $v) { 
      $k = preg_match ('/^\x00(?:.*?)\x00(.+)/', $k, $matches) ? $matches [1] : $k; 
      if (in_array ($k, $this->getAvoidedFields())) { 
       $array [$k] = ""; 
      } else { 

       // if it is an object recursive call 
       if (is_object ($v) && $v instanceof AbstractEntity) { 
        $array [$k] = $v->toArray(); 
       } 
       // if its an array pass por each item 
       if (is_array ($v)) { 

        foreach ($v as $key => $value) { 
         if (is_object ($value) && $value instanceof AbstractEntity) { 
          $arrayReturn [$key] = $value->toArray(); 
         } else { 
          $arrayReturn [$key] = $value; 
         } 
        } 
        $array [$k] = $arrayReturn; 
       } 
       // if it is not a array and a object return it 
       if (! is_object ($v) && !is_array ($v)) { 
        $array [$k] = $v; 
       } 
      } 
     } 

     return $array; 
    } 
} 
Problemi correlati