Skip to content

Commit 70b6f26

Browse files
seiflotfynikhilm
authored andcommitted
Serialize output to JSON in Java (#64)
* Serialize output to JSoN in Java * catch json serialization exception * print out a proper error message on error during serialization
1 parent 22cc283 commit 70b6f26

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

images/examples/java/src/main/java/example/Hello.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public ArrayList<UserInfo> myHandlerList(ArrayList<UserInfo> arrayList, Context
4949
return arrayList;
5050
}
5151

52-
public static void myHandlerPOJO(RequestClass request, Context context){
53-
System.out.println(String.format("Hello %s %s" , request.firstName, request.lastName));
52+
public static String myHandlerPOJO(RequestClass request, Context context){
53+
return String.format("Hello %s %s" , request.firstName, request.lastName);
5454
}
5555
}

images/java/src/main/java/io/iron/lambda/Launcher.java

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,15 @@ private void runMethod(Method lambdaMethod, String payload, Class cls, String ha
131131
if (!processed) {
132132
System.err.println(String.format("Handler %s with simple, POJO, or IO(input/output) types not found", handlerName));
133133
}
134+
135+
try {
136+
String jsonInString = ClassTypeHelper.gson.toJson(result);
137+
System.out.println(jsonInString);
138+
}
139+
catch (Exception e) {
140+
System.out.println("{\"error\": \"" + ClassTypeHelper.gson.toJson(e.toString()) + "\"}");
141+
System.exit(1);
142+
}
134143
}
135144

136145
private void launchMethod(String[] packageHandler, String payload) throws Exception {
@@ -195,10 +204,6 @@ private void launchMethod(String[] packageHandler, String payload) throws Except
195204
});
196205

197206
Class returnType = matchedArray[0].getReturnType();
198-
if (!returnType.getTypeName().equals("void")) {
199-
System.err.println(String.format("Handler can only have 'void' return type. Found '%s'.", returnType.getTypeName()));
200-
System.exit(1);
201-
}
202207
runMethod(matchedArray[0], payload, cls, handlerName);
203208
}
204209

0 commit comments

Comments
 (0)