json - 如何从 Play 应用程序中的 play.mvc.Result 对象中提取结果内容?

标签 json playframework playframework-2.0

实际上我正在从一个 Play 应用程序重定向到另一个 Play 应用程序,最后我收到作为结果对象的响应..下面是两个应用程序中的操作。我正在从应用程序 1 重定向到应用程序 2。应用程序 2 将返回我需要提取的 JSON 字符串。

如何从 Result 对象中检索 JSON 内容?

应用1:

public static Result redirectTest(){

    Result result =  redirect("http://ipaddress:9000/authenticate");
    /*** here I would like to extract JSON string from result***/
    return result;
}

应用2:
@SecuredAction
public static Result index() {
     Map<String, String> response = new HashMap<String, String>();
     DemoUser user = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);

       for(BasicProfile basicProfile: user.identities){
           response.put("name", basicProfile.firstName().get());
           response.put("emailId", basicProfile.email().get());
           response.put("providerId", basicProfile.providerId());
           response.put("avatarurl", basicProfile.avatarUrl().get());
       }

    return ok(new JSONObject(response).toString());
}

最佳答案

使用 JavaResultExtractor,例如:

Result result = ...;
byte[] body = JavaResultExtractor.getBody(result, 0L);

拥有一个字节数组,您可以从 Content-Type header 中提取字符集并创建 java.lang.String:
String header = JavaResultExtractor.getHeaders(result).get("Content-Type");
String charset = "utf-8";
if(header != null && header.contains("; charset=")){
    charset = header.substring(header.indexOf("; charset=") + 10, header.length()).trim();
}
String bodyStr = new String(body, charset);
JsonNode bodyJson = Json.parse(bodyStr);

上面的一些代码是从 play.test.Helpers 复制的

关于json - 如何从 Play 应用程序中的 play.mvc.Result 对象中提取结果内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26301140/

相关文章:

json - Play Framework 自动 JSON 编码

ajax - 无法使用动态 JSON

javascript - LinkedIn API - 如何在公司A中找到用户1和用户2之间的相互连接

javascript - Firebase:查询返回 null

scala - 有 ScalaTest 或匹配器,使用 PlaySpec Playframework 和 Scala 进行测试

java - play框架的输入文本值总是传递0

playframework - play 2框架编译错误

json - 核心数据和JSON问题

java - 如何在 Play Framework 模型中导入 java 扩展?

java - Play .exceptions.JavaExecutionException : id to load is required for loading