victuxbb / jsonpatch
JSON Patch (http://tools.ietf.org/html/rfc6902) 的实现
v1.0.1
2015-01-12 00:33 UTC
Requires
- php: >=5.3.3
Requires (Dev)
- phpunit/phpunit: 4.3.*
This package is not auto-updated.
Last update: 2024-09-24 03:08:08 UTC
README
PHP中的JSON Patch (http://tools.ietf.org/html/rfc6902) 实现
安装
将 victuxbb/jsonpatch
添加到你的 composer.json
文件中
{ "require": { "victuxbb/jsonpatch": "@stable" } }
或在你的项目根目录内
$ composer require victuxbb/jsonpatch @stable
文档
以这样的目标JSON为例
$targetJSON ='{"baz": "qux","foo": "bar"}';
和一个包含JSON字符串的变量进行操作
$patchOperations = '[ { "op": "replace", "path": "/baz", "value": "boo" } ]';
创建一个Patcher实例,使用"patch"方法获取json结果
$patcher = new Patcher(); $result = $patcher->patch($targetJSON,$patchOperations);
$result将包含
{"baz":"boo","foo":"bar"}
与FOSRestBundle和JMSSerializer的典型用例
public function patchUserAction(Request $request,User $user) { $json = $request->getContent(); $jps = $this->get('json_patch_service'); //symfony service that loads Patcher.php $serializer = $this->get("jms_serializer"); $serializerGroup = array('view'); $sc = SerializationContext::create(); $sc->setGroups($serializerGroup); $jsonUser = $serializer->serialize($user,'json',$sc); //Generating the json target of object that we want to update $jsonUser = $jps->patch($jsonUser,$json); //json result with the changes applied of the json operations $dc = DeserializationContext::create(); $dc->setAttribute('target',$user); //Restore the doctrine entity object with deserialization and targeting the object with DeserializationContext $serializer->deserialize($jsonUser,'Groupalia\BizApiBundle\Entity\User','json',$dc); $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush(); $response = new Response(); $response->setStatusCode(200); return $response; }
感谢
*https://github.com/javadegava
*http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/