如何在php中反序列化嵌套的json数组?

时间:2015-06-23 12:26:17

标签: php json

我有这个json结构:

[
  {"product":
             {"category_id":1,
              "created_at":"2015-06-13 17:49:58",
              "description":"CF77 COIN FINDER",
              "url_image":"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg",
              "name":"CF77 COIN FINDER",
              "pid":12,
              "price":500.0
             },
   "product_quantity":3
  },
  {"product":
             {"category_id":1,
              "created_at":"2015-06-13 17:49:58",
              "description":"JEOSONAR 3D DUAL SYSTEM",
              "url_image":"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg",
              "name":"JEOSONAR 3D DUAL SYSTEM",
              "pid":15,
              "price":500.0
             },
   "product_quantity":1
   }
]

对于反序列化,我创建了这两个类

产品类:

class Product
{
    public $pid;
    public $name;
    public $price;
    public $category_id;
    public $url_image;
    public $description;
    public $created_at;
    public $updated_at;

    public function __construct( $pid, $name, $price, $category_id, $url_image, $description, $created_at, $updated_at )
    {
        $this->pid = $pid;
        $this->name = $name;
        $this->price = $price;
        $this->category_id = $category_id;
        $this->url_image = $url_image;
        $this->description = $description;
        $this->created_at = $created_at;
        $this->updated_at = $updated_at;
    }

    public static function createFromJson( $jsonString )
    {
        $object = json_decode( $jsonString );
        return new self( $object ->pid, $object ->name, $object ->price, $object ->category_id, $object ->url_image, $object ->description, $object ->created_at, $object ->updated_at );
    }

}

命令类:

class Command {

    public $product;
    public $product_quantity;

    public function __construct( $product, $product_quantity ){
        $this->product=$product;
        $this->product_quantity=$product_quantity;
    }

    public static function createFromJson( $jsonString )
    {
        $object = json_decode( $jsonString );
        return new self( Product::createFromJson( $object->product), $object ->product_quantity );
    }

}

对于简单的json结构,我可以使用createFromJson方法,但对于数组,我找不到一种方法来反序列化上面的json结构。

如何反序列化json数组结构?

1 个答案:

答案 0 :(得分:0)

我只是确保它始终是一个数组,然后根据它返回。我想象这样的事情:

public static function createFromJson( $jsonString )
{
    $json = json_decode( $jsonString );
    if (!is_array($json)) $json = array($json);
    $return = array();
    foreach($json as $object) {
        $return[] new self( Product::createFromJson( $object->product), $object ->product_quantity );
    }
    return count($return) == 1 ? $return[0] : $return;
}

这将捕获数组中的所有命令,如果只解码了一个命令,则只返回一个命令。虽然,我个人总是会返回数组,因此该方法只有一个返回类型。