我有一个Java应用程序发送json内容到我的服务器(C++)。我的服务器,我收到的JSON,做解析,验证等,并发送响应与JSON了。 我在我的Java应用程序一个要求,即有此JSON体(例如):GSON反序列化/序列化层次类
{
"a": "a",
"b": "b",
"searchMethod": {
"searchByUser": {
"userId": "userId"
}
}
}
但相同的命令,我可以有其他searchMethod
:
{
"a": "a",
"b": "b",
"searchMethod": {
"searchByEmail": {
"email": "[email protected]"
}
}
}
因此,当用户做要求我们可以向我的服务器发送这两个不同的json bodys中的一个。我永远不知道我们发送了什么searchMethod
。这部分(检查用户发送的searchMethod是什么等),当我收到json时,我在我的C++服务器上执行操作。所以在我的Java应用程序中,我只需要使用gson发送一个searchMethod
对象与他们的内容。
这是我班的要求去做:
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;
}
}
}
我已经实现了领域a
和b
,因为它总是在这个要求是相同的。在这个类中,fromStringJson(String data)
接收包含用户尝试发送的所有json的数据字符串字段。在这个函数中,我使用gson.fromJson
将这个字符串转换为我的RequestExample
类的json对象类型。
所以主要问题是:如何适应我的RequestExample
类将字符串转换为json对象,而不管searchMethod
的类型如何。就像我在我的Java应用程序中所说的,我不需要知道用户如何选择seachMethod
。在我的服务器是,但这部分我已经实现。所以现在,我只需要将请求发送到我的服务器。
感谢您的答复。我了解你的代码,但我有一个疑问。什么是对象? searchByUser还是searchByEmail?在这张地图中,我需要定义一些对象,但我不知道用户选择的对象类型。你明白我的疑问吗?同样的命令可以有searchByUser或searchByEmail ..当我收到我的字符串数据时,我不知道用户放什么searchMethod – RMRMaster
对不起。我不需要用户java hiearchy。我只能使用像这样的地图: Map> searchMethod,因为我的服务器中的json内容有关的阀值。通过这种方式,我可以发送searchMethod和内部的c + +服务器我解析json并进行验证:) –
RMRMaster
据我了解,您找到了解决方案,所以我编辑了其他人的答案 –