AWS Lambda Java响应不支持嵌套对象? [英] AWS lambda java response does not support nested objects?

查看:150
本文介绍了AWS Lambda Java响应不支持嵌套对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,所以这可能与AWS lambda根本无关.但是,lambda对输入/输出对象拥有如此自由,我以为这是罪魁祸首.

I'm new to Java so this may not be related to AWS lambda at all. However, lambda takes such liberties with input/output objects that I'm assuming it's the culprit here.

我正在构建我的第一个lambda函数,并想返回一个简单的JSON结构(此示例进一步简化):

I'm building my first lambda function and want to return a simple JSON structure (simplified further for this example):

{
  "document" : "1",
  "person" : { "name" : "John Doe" }
}

但是,当lambda序列化JSON时,它总是将"person"设置为空白对象!

However, when lambda serializes the JSON it always sets "person" to a blank object!

{
  "document": "1",
  "person": {}
}

这是我的完整代码:

 - test1.java
package handler_test;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class test1 implements RequestHandler<String, ResponseClass> {
    @Override
    public ResponseClass handleRequest(String input, Context context) {
      return new ResponseClass();
    }
}

 - ResponseClass.java
package handler_test;
import org.json.JSONException;
import org.json.JSONObject;
public class ResponseClass {
    String document;
    JSONObject person;

    public String getdocument() {
        return "1";
    }

    public JSONObject getperson() {
        try {
            return new JSONObject("{ \"name\" : \"John Doe\" }");
        } catch (JSONException e1) {
            System.out.println("error creating jsonobject");
            return null;
        }
    }

    public ResponseClass() {
    }
}

我已经尝试了数十种变体,使用对象而不是JSONObjects,将getperson输出转换为字符串(如果我想要一个字符串,则可以使用),等等.如果我存储值并将它们打印到记录器中,没关系.但是,一旦我尝试通过lambda返回它,它就会变成梨形.我已经梳理了"net",除了亚马逊的"greetings"示例代码(仅包含两个字符串)之外,在AWS-lambda java响应对象上找不到更多内容.任何建议,不胜感激!

I've tried this with dozens of variations, using objects instead of JSONObjects, converting getperson output to a string (which works, if I wanted a string), etc. If I store the values and print them to the logger, it's fine. But as soon as I try to return it through lambda it goes pear-shaped. I've combed the 'net and can't find anything more on AWS-lambda java response objects beyond Amazon's "greetings" sample code, which just includes two strings. Any suggestions greatly appreciated!

推荐答案

我使用流处理程序解决了此问题,不仅有效,而且您拥有更多的控制权和更少的代码!我将gson用于JSON序列化/反序列化,并将Apache IOUtils用于将inputsteam转换为字符串.正如我已经使用Request和Response类编写的那样,尽管可以摆脱所有的getter和setter代码,但我继续使用它们.

I solved this using the stream handlers, and not only does it work but you have more control and less code! I used gson for JSON serialization/deserialization and the Apache IOUtils for converting inputsteam to a string. As I'd already written it using the Request and Response classes, I continued using those, although I was able to get rid of all the getter and setter code.

两个注意事项: 1. gson将输出Response类的所有非null属性,即使 如果它们被声明为私有,那么如果您不想使用某些值 向后吐口水,确保在最后一行之前将它们设置为null. 2.在将Eclipse IDE与AWS插件一起使用时,除非可以找到RequestHandler,否则它将不会将代码上传到AWS!因此,我有一个存根函数,该存根函数会立即被覆盖.

Two notes: 1. gson will output all non-null attributes of the Response class, even if they're declared private, so if there are values you don't want to spit back be sure to set them to null before the final line. 2. When using Eclipse IDE with the AWS plugin, it will not upload the code to AWS unless it can find a RequestHandler! Thus I have a stub function that is immediately overridden.

import com.google.gson.*;
import org.apache.commons.io.IOUtils;
import com.amazonaws.services.lambda.runtime.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

public class Intel implements RequestStreamHandler, RequestHandler<Object, Object> {
    @Override
    public Object handleRequest(Object input, Context context) {
        return null;
    }

    @Override
    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        Request req = new Gson().fromJson(IOUtils.toString(inputStream, "UTF-8"), Request.class);
        Response resp = new ResponseClass();
            resp.id = 1;
            resp.person.name = req.name;
            et_home_phone(req.name);
        outputStream.write(new Gson().toJson(resp).getBytes(Charset.forName("UTF-8")));
    }

    private void get_home_phone(String name) {
        // call external API -- stub example!  Assumes only one phone returned
        // in the format { "number" : "123-456-7890", "type" = "home" }
        // gson magic assures they get copied to the keys of the same name
        HttpGet httpGet = new HttpGet(phoneURL + "/" + name));
        HttpResponse httpResponse = client.execute(httpGet);
        resp.phone[0] = new Gson().fromJson(IOUtils.toString(httpResponse .getEntity().getContent(), "UTF-8"), Response.Phone.class);
    }
}

public class Response {
    public class Person {
        String name;
    }
    public class Phone {
        String number;
        String type;
    }
    public Integer id;
    public Person person = new Person();
    public Phone[] phone = new Phone[5];
}

这篇关于AWS Lambda Java响应不支持嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆