Skip to content

Instantly share code, notes, and snippets.

@fehmicansaglam
Created November 3, 2012 09:49
Show Gist options
  • Save fehmicansaglam/4006845 to your computer and use it in GitHub Desktop.
Save fehmicansaglam/4006845 to your computer and use it in GitHub Desktop.
Play Custom Json Result
package controllers;
import static controllers.result.CustomJsonResult.renderCustomJson;
import java.util.Arrays;
import java.util.List;
import play.mvc.Controller;
public class Application extends Controller {
public static void index() {
Double d = 2.02121;
String s = "ttt";
int a = 5;
List<String> names = Arrays.asList("abuzer", "kadayıf");
String bb = "ds";
renderCustomJson(names, a, s, d);
// 404 status kodu ile
// renderCustomJson(404, names, a, s, d);
}
}
package controllers.result;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer;
import play.exceptions.UnexpectedException;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import play.mvc.results.Result;
import com.google.gson.Gson;
public class CustomJsonResult extends Result {
private final String json;
private final int status;
private CustomJsonResult(final Object... args) {
if (args.length > 0 && args[0] instanceof Integer
&& LocalVariablesNamesTracer.getAllLocalVariableNames(args[0]).isEmpty()) {
this.status = (Integer) args[0];
} else {
this.status = 200;
}
Map<String, Object> result = new HashMap<String, Object>();
for (Object o : args) {
List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o);
for (String s : names) {
result.put(s, o);
}
}
this.json = new Gson().toJson(result);
}
@Override
public void apply(final Request request, final Response response) {
try {
response.status = this.status;
String encoding = this.getEncoding();
this.setContentTypeIfNotSet(response, "application/json; charset=" + encoding);
response.out.write(this.json.getBytes(encoding));
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
public static void renderCustomJson(final Object... args) {
throw new CustomJsonResult(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment