Convert Python dict to Map from python_server_entry_point
texervn opened this issue · comments
Hello!
This is not a bug, but I would like to ask a question on how to convert dictionary to JavaMap more efficient. I can achieve the goal by creating a new instance of JavaGateway and use its _gateway_client
for MapConverter.
What I want is that we convert result
to JavaMap object without using JavaGateway. Is there any way to only use _gateway_client
directly from the ClientServer below?
I really appreciate your help.
Here is my code:
hello.py
from py4j.clientserver import ClientServer, JavaParameters, PythonParameters
from py4j.java_collections import MapConverter
from py4j.java_collections import JavaMap
from py4j.java_gateway import JavaGateway, GatewayParameters
class SimpleHello(object):
@staticmethod
def sayHello(service: str, params: JavaMap) -> JavaMap:
gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_convert=True)
)
result = {"a": "b", "c": 1, "d": [1, 2, 3], "e": [{"x": "y"}]}
result_map = MapConverter().convert(result, gateway._gateway_client)
return result_map
class Java:
implements = ["com.hello.IHello"]
simple_hello = SimpleHello()
ClientServer(
java_parameters=JavaParameters(auto_convert=True),
python_parameters=PythonParameters(),
python_server_entry_point=simple_hello
)
IHello.java
package com.hello;
import java.util.Map;
public interface IHello {
public Map<String, Object> sayHello(
String service,
Map<String, Object> params
);
}
SingleThreadClientApplication.java
package com.hello;
import java.util.Map;
import org.json.JSONObject;
import py4j.ClientServer;
public class Main {
public static void main(String[] args) {
ClientServer clientServer = new ClientServer(null);
IHello hello = (IHello) clientServer.getPythonServerEntryPoint(new Class[] { IHello.class });
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 30);
JSONObject small = new JSONObject();
small.put("color", "Blue");
small.put("size", "Big");
jsonObject.put("config", small);
Map<String, Object> paramsMap = jsonObject.toMap();
System.out.println(hello.sayHello("service", paramsMap));
clientServer.shutdown();
}
}
i just wondering how to use params: JavaMap, which is not used in your hello.py demo ? thanks a lot
Oh, I see. There is actually a function that takes JavaMap params and returns the result.
For example:
result = my_function(params)
For the simplicity, I assigned the result directly.
Thanks.