JSON を常に次の形式で送信する RESTful サードパーティ API を使用しています。
{
"response": {
...
}
}
...
Java POJO にマップし直す必要がある応答オブジェクトはどこにありますか。たとえば、JSON には、Fruit
POJOにマップし直すべきデータが含まれていることがあります。
{
"response": {
"type": "orange",
"shape": "round"
}
}
Employee
...また、JSON には、 POJOにマップし直すべきデータが含まれている場合があります。
{
"response": {
"name": "John Smith",
"employee_ID": "12345",
"isSupervisor": "true",
"jobTitle": "Chief Burninator"
}
}
したがって、RESTful API 呼び出しに応じて、次の 2 つの JSON 結果を 2 つのうちの 1 つにマップする必要があります。
public class Fruit {
private String type;
private String shape;
// Getters & setters for all properties
}
public class Employee {
private String name;
private Integer employeeId;
private Boolean isSupervisor;
private String jobTitle;
// Getters & setters for all properties
}
残念ながら、このサード パーティの REST サービスが常に{ "response": { ... } }
JSON の結果を返すという事実を変えることはできません。しかし、そのようなresponse
バックを aFruit
またはEmployee
.
最初に、Jacksonを試してみましたが、あまりうまくいきませんでしたが、私が望んでいたほどには構成可能ではありませんでした。そのため、JSONをPOJOにマッピングするためにXStreamを使用しようとしています。JettisonMappedXmlDriver
これが私が持っているプロトタイプコードです:
public static void main(String[] args) {
XStream xs = new XStream(new JettisonMappedXmlDriver());
xs.alias("response", Fruit.class);
xs.alias("response", Employee.class);
// When XStream sees "employee_ID" in the JSON, replace it with
// "employeeID" to match the field on the POJO.
xs.aliasField("employeeID", Employee.class, "employee_ID");
// Hits 3rd party RESTful API and returns the "*fruit version*" of the JSON.
String json = externalService.getFruit();
Fruit fruit = (Fruit)xs.fromXML(json);
}
残念ながら、これを実行すると例外が発生します。これは、2 つの異なる Java オブジェクトにxs.alias("response", ...)
マッピングしているためです。response
Caused by: com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field me.myorg.myapp.domain.Employee.type
---- Debugging information ----
field : type
class : me.myorg.myapp.domain.Employee
required-type : me.myorg.myapp.domain.Employee
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /response/type
line number : -1
version : null
-------------------------------
API が常に同じ「ラッパー」 JSON オブジェクトを送り返すという事実を回避するにはどうすればよいresponse
でしょうか? 私が考えることができる唯一のことは、最初に次のように文字列置換を行うことです。
String json = externalService.getFruit();
json = json.replaceAll("response", "fruit");
...
しかし、これは醜いハックのようです。XStream (または別のマッピング フレームワーク) は、この特定のケースで私を助ける何かを提供しますか? 事前に感謝します。