I have this json structure:
[
{"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
}
]
And for deserialization, I have created these two classes
Product class:
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 );
}
}
Command class:
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 );
}
}
For simple json structure, I can use the createFromJson
method, but for arrays I couldn't find a way to deserialize the above json structure.
How can i deserialize json array structure?
I would simply make sure its always an array, and return based on that. I imagine something like this:
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;
}
This will capture all the commands in an array, and return just one Command if only one was decoded. Although, personally I would always return the array, so the method has a single return type.