php Symfony2 JSON 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5811647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symfony2 JSON example
提问by ktolis
I'm trying to set up a json example using symfony2.
I've created a test bundle, a test entity ("Message"), set up the orm etc
The Message(table) has the following columns: id, title, text
I'm trying to expose a route */mydomain/message that would expose a json interface to messages table (a small list)
我正在尝试使用 symfony2 设置一个 json 示例。
我创建了一个测试包,测试实体(“信息”),成立了ORM等
的信息(表)具有以下列:ID,标题,文字
,我试图揭露路线* / MYDOMAIN /消息这将向消息表公开一个 json 接口(一个小列表)
The first methodology I tried was:
我尝试的第一种方法是:
Create a MessageController class that uses Symfony\Component\HttpFoundation\Response
and has a function like this:
创建一个 MessageController 类,该类使用Symfony\Component\HttpFoundation\Response
并具有如下功能:
public function testAction() {
$response = new Response(json_encode(**code_req_here**));
return $response;
}
and set a route like so:
并设置如下路线:
test:
pattern: /test
defaults: { _controller: myProjectmyTestBundle:Message:test, _format: json}
requirements: { _format: (xml|json), _method: GET }
- is this a correct methodology?
- what do I put on the
code_req_here
?
- 这是一种正确的方法吗?
- 我该穿什么
code_req_here
?
the second methodology I tried was by using the FOS/RestBundle but didn't manage to complete the guide correctly as I understand, so
我尝试的第二种方法是使用 FOS/RestBundle,但没有按照我的理解正确完成指南,所以
- please provide a small guide on how to do (just) this with FOS/RestBundle
- 请提供有关如何(仅)使用 FOS/RestBundle 执行此操作的小指南
采纳答案by mask8
is this a correct methodology?
这是一种正确的方法吗?
Yes I like it but I would modify the routing rule a bit like this:
是的,我喜欢它,但我会像这样修改路由规则:
test:
pattern: /test.{_format}
defaults: { _controller: myProjectmyTestBundle:Message:test, _format: json}
requirements: { _format: (xml|json), _method: GET }
what do I put on the code_req_here?
我在 code_req_here 上放什么?
Put the array that you want to convert to json format. ex. array(array('id' => 1, 'value' => 'test'), array('id' => 2, 'value' => 'smart'))
把你要转换成json格式的数组放进去。前任。array(array('id' => 1, 'value' => 'test'), array('id' => 2, 'value' => 'smart'))
回答by jerson
I recommend using
我建议使用
http://jmsyst.com/bundles/JMSSerializerBundle
http://jmsyst.com/bundles/JMSSerializerBundle
$serializer = $container->get('jms_serializer');
$serializer->serialize($data, 'json'); // json|xml|yml
$data = $serializer->deserialize($inputStr, $typeName, $format);