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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:33:48  来源:igfitidea点击:

Symfony2 JSON example

phpjsonrestsymfony

提问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\Responseand 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 }  
  1. is this a correct methodology?
  2. what do I put on the code_req_here?
  1. 这是一种正确的方法吗?
  2. 我该穿什么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,但没有按照我的理解正确完成指南,所以

  1. please provide a small guide on how to do (just) this with FOS/RestBundle
  1. 请提供有关如何(仅)使用 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);