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

 

 

 

你可能感兴趣的:(response)