我有一个Spring引导应用程序,我在其中使用RestTemplate调用Rest API,并且收到以下JSON格式的响应:
{
"data": [
{
"id": "1",
"type": "type1",
"config": {
"property1" : "value1",
"property2" : "value2"
}
},
{
"id": "2",
"type": "type2",
"config": {
"property3" : "value3",
"property4" : "value4",
"propArray": [ "element1", "element2"]
}
}
]
}
“数据”数组中的各个元素具有几种不同的结构(上面的2个示例),在此我想根据各个元素的类型来映射不同的类类型,具体取决于元素“类型”的值。
例如,值“ type1”应映射到Class类型“ Type1”的对象,依此类推。
我有如下创建的类: MyResponse:
public Class MyResponse {
List<Data> data;
..
\\getter and setters
}
数据:
public Interface Data {}
类型1:
public Class Type1 implements Data {
private String property1;
private String property2;
..
\\getter and setters
}
Type2:
public Class Type1 implements Data {
private String property3;
private String property4;
private List<String> propArray;
..
\\getter and setters
}
如何映射以上条件结构?
答案 0 :(得分:2)
我只能想到的是获取返回值String,将其转换为JSONObject并对其进行处理以创建您的类的实例。例如,
String response = restTemplate.<your-uri>
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.get(type).equals(type1) {
Type1 type1 = new Type1();
// set values
} else if (jsonObject.get(type).equals(type2) {
Type2 type2 = new Type2()
// set values
}
但是,这是不可扩展的,如果要添加越来越多的类型,将很难维护干净的代码。
执行此操作的另一种方法是创建一个通用类,并以该类的列表的形式接收响应。通过这种方式,Spring-boot / Jackson可以进行映射。同样,您必须添加代码以从该常规类创建其他类。正如Sam在评论中指出的那样,这将是首选,因为Jackson的速度比JSONObject的快。这是示例类,
class Response {
private Integer id;
private String type;
private Map<String, Object> config;
}
您仍然必须检查类型并映射到相应的类。
我会考虑是否可以重新构造您发送的设计/响应(如果您对其有控制权),而不是编写这样的凌乱代码。