Reputation: 89
I have a java app that send json content to my server (c++). I my server i receive the json, do the parse, the validation, etc and send back the response with json too. I have one request in my java app that have this json body (example):
{
"a": "a",
"b": "b",
"searchMethod": {
"searchByUser": {
"userId": "userId"
}
}
}
But for the same command i can have other searchMethod
:
{
"a": "a",
"b": "b",
"searchMethod": {
"searchByEmail": {
"email": "[email protected]"
}
}
}
So, when the user do the request we can send to my server one of this two different json bodys. I never know what searchMethod
we send. This part (check what searchMethod the user send, etc), i do in my c++ server when i receive the json. So in my java app i only need to use the gson to send a searchMethod
object with their content.
This my class to do the request:
public class RequestExample implements SerializableJSON
{
public String a;
public String b;
public RequestExample(String a, b)
{
this.a = a;
this.b = b;
}
public static RequestExample fromStringJson(String data)
{
try
{
Gson gson = new Gson();
return gson.fromJson(data, RequestExample.class);
}
catch(Exception e)
{
return null;
}
}
public static RequestExample fromBytesJson(byte[] data)
{
if (data == null) return null;
try
{
String str = new String(data, "utf-8");
return fromStringJson(str);
}
catch (Exception e)
{
return null;
}
}
@Override
public String toJsonString()
{
try
{
Gson gson = new Gson();
return gson.toJson(this);
}
catch(Exception e)
{
return null;
}
}
@Override
public byte[] toJsonBytes()
{
try
{
return this.toJsonString().getBytes("utf-8");
}
catch (Exception e)
{
return null;
}
}
}
I already implement the fields a
and b
because its always the same in this request. In this class the fromStringJson(String data)
receive the data string field that contain all json that the user try to send. In this function i use the gson.fromJson
to convert this string to a json object type of my RequestExample
class.
So the main question is: How to adapt my RequestExample
class to convert the string to a json object regardless of the type of searchMethod
. Like i said in my java app i dont need to know how seachMethod
the user choose. In my server yes, but this part i already implement. So for now, i only need to send the request to my server.
Upvotes: 1
Views: 356
Reputation: 1206
If you don't use field searchMethod
, you can implement it like a Map
private Map<String, Object> searchMethod = new HashMap<>();
or
private Map<String, Map<String,Object>> searchMethod = new HashMap<>();
or
private Map<String, Map<String,String>> searchMethod = new HashMap<>();
Upvotes: 1