简体   繁体   English

PHP数组与对象到JSON字符串

[英]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. 我想将包含对象数组的对象“ Resonse”转换为JSON字符串。

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. 消息对象具有私有属性类型,并且消息带有getter和setter方法。

So does anybody know how to convert this to a json string? 那么有人知道如何将其转换为json字符串吗? Btw, I have the same question for converting it to XML. 顺便说一句,我有同样的问题将其转换为XML。

Thanks for the help. 谢谢您的帮助。

Check http://php.net/manual/en/function.serialize.php 检查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() . 您可以将Response对象转换为关联数组,然后将该数组传递给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. 对于XML转换,我编写了一个简单的类,可以将上述代码产生的$response数组转换为DOMDocument对象或XML字符串。 You can find it here: code.google.com/p/array-to-domdocument/ 您可以在这里找到它: 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. 如果定义了私有变量,则简单的json_encode将不会有任何可用的输出。 You can created functions within your object to return a json-encoded string. 您可以在对象中创建函数以返回json编码的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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