简体   繁体   中英

PHP array with objects to json string

I would like to convert an object 'Resonse' that contains an array with objects to a JSON string.

Example of the data structure:

$response = new model_ObjectReponse();
$error1 = new model_Message('error', 'test error 1');
$error2 = new model_Message('error', 'test error 2');
$error3 = new model_Message('error', 'test error 3');
$response->add($error1);
$response->add($error2);
$response->add($error3);
$output = json_encode($response);
print $output;

The message objects have the private properties type and message with getters and setters.

So does anybody know how to convert this to a json string? Btw, I have the same question for converting it to XML.

Thanks for the help.

Check http://php.net/manual/en/function.serialize.php

This method will allow you to save object as string. You can also unserialize object, anyway storing objects as string is not a good practice.

You can convert your Response object to an associative array and pass that array on to json_encode() . Something like this:

foreach ($response->getMessages() as $message)
  $responseArray['messages'][] = array(
    'type' => $message->getType(),
    'message' => $message->getMessage()
  );

json_encode($responseArray);

For the XML conversion, I wrote a simple class that can convert the $response array produced by the code above to a DOMDocument object or an XML string. You can find it here: code.google.com/p/array-to-domdocument/

Your class definition could be the problem here. If you have private variables defined, a simple json_encode won't any usable output. You can created functions within your object to return a json-encoded string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM