Neo4j: Streaming JSON responses

To lift server performance, when we query some data and result is hug,  in which case,  large memory will be used to produce the result json string. 

One solution is to use streaming JSON responses.

 @Path("/fof/{userName}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getFOF(final @PathParam("userName") String userName) throws JSONException {
 	StreamingOutput stream = new StreamingOutput() {
	    @Override
	    public void write(OutputStream os) throws IOException, WebApplicationException {
		// TODO Auto-generated method stub
		JsonGenerator jg = objectMapper.getJsonFactory().createJsonGenerator(os, JsonEncoding.UTF8);
		jg.writeStartObject();
		jg.writeFieldName("fofs");
		jg.writeStartArray();

		try (Transaction tx = template.getGraphDatabaseService().beginTx()) {
		    Iterable<User> fofs = userRepo.getFriendsOfFriends(userName);
		    Iterator<User> it = fofs.iterator();
		    while (it.hasNext()) {
			User fof = it.next();
//			jg.writeString(fof.getName());
			jg.writeObject(fof);
		    }
		    tx.success();

		    jg.writeEndArray();
		    jg.writeEndObject();
		    jg.flush();
		    jg.close();
		}
	    }
	};

	return Response.ok().entity(stream).type(MediaType.APPLICATION_JSON).build();
    }

 

 

Warning:  jg.writeObject(fof)  will write the whole user object to result, which is not my expected.  I just want to partial properties in the User object while ingore others. How to satisify my needs?

 

the similar commands are

http://stackoverflow.com/questions/20978383/convert-same-pojo-into-json-and-xml-but-ignore-some-properties-for-json

https://github.com/FasterXML/jackson-databind/issues/95

 

The simple way is to manually marshell you expected properties likes 

			jg.writeStartObject();
			jg.writeFieldName("name");
			jg.writeString(fof.getName());
			jg.writeFieldName("phoneNum");
			jg.writeString(fof.getPhoneNumber());
			jg.writeEndObject();

 

The result json  for query 

curl http://localhost:7474/fifo/user/fof/liwk

 is

{"fofs":[{"name":"losiy","phoneNum":"15658653696"},{"name":"jack","phoneNum":null}]}

 

 

 

 

 

 

References

http://neo4j.com/docs/stable/server-unmanaged-extensions.html#server-unmanaged-extensions-streaming

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值