How to convert php class to json

1.Create a PHP classs with below code

<?php
class JsonObject {
public $statusMessage;
public $statusCode;
public $data;
function __construct ($statusMsg, $code, $json)
{
$this->statusMessage = $statusMsg;
 $this->statusCode = $code;
 $this->data = $json;
 }

}

2.Now  create an object of above php class like

$Obj = new JsonObject ("success", "200","json data string ");

3.Now use get_object_vars($Obj) and json_encode() function in php as shown below.

echo json_encode(get_object_vars($Obj));

4.Output will be ,we can also give an array in place of data and it will convert it to json format accordingly.

{
"statusMessage": "success",
"statusCode": 200,
"data":"json data string "
}
Advertisements
This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s