を作るために、私は実際に私は、JSONは(期待JSON)下記の形式になりたい私に次の応答Gsonカスタムデシリアライズ異なるJSON出力
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 123,
"hits": [
{
"_index": "123",
"_type": "bar",
"_id": "123",
"_score": 323,
"_source": {
"employeeNo": 239,
"employeeName": "John",
"employeeRank": 21,
"employeeNationality": "Indian",
"employeeNickName": "KingKong"
}
},
{
"_index": "234",
"_type": "bar",
"_id": "124",
"_score": 324,
"_source": {
"employeeNo": 241,
"employeeName": "Sunny",
"employeeRank": 19,
"employeeNickName": "Jakk"
}
},
{
"_index": "235",
"_type": "bar",
"_id": "125",
"_score": 325,
"_source": {
"employeeNo": 251,
"employeeName": "Pollard",
"employeeRank": 10
}
}
]
},
"aggregations": {
"foo": {
"buckets": [
{
"key": 123,
"doc_count": 123
}
]
}
}
}
を与えるREST APIサービスを持っています
これを達成するための[
{
"employeeNo": 239,
"employeeName": "John",
"employeeRank": 21,
"employeeNationality": "Indian",
"employeeNickName": "KingKong"
},
{
"employeeNo": 241,
"employeeName": "Sunny",
"employeeRank": 19,
"employeeNickName": "Jakk"
},
{
"employeeNo": 251,
"employeeName": "Pollard",
"employeeRank": 10
}
]
は、私は次のコードを書いている
List<Map<String, String>> myResults = new ArrayList<Map<String, String>>();
Gson serializer = new GsonBuilder().create();
String responseDetails = doHttpPost(urlToQuery, serializer.toJson(requestBody));
Map<String,Object> restResponse = (Map<String,Object>)serializer.fromJson(responseDetails,Object.class);
if(restResponse.containsKey("hits")){
Map<String, Object> hits = (Map<String, Object>) restResponse.get("hits");
if(hits.containsKey("hits")) {
List<Map<String, Object>> hitDetails = (List<Map<String, Object>>) hits.get("hits");
for (Map<String, Object> hitDetail : hitDetails) {
Map<String, Object> sources = (Map<String, Object>) hitDetail.get("_source");
myResults.add(sources);
}
}
}
上記のコードでは、私はresponseDetails
変数に入れた文字列としてREST APIからの応答を取得します。また、私はそれを反復処理し、私の期待JSON応答を形成
Map<String,Object> restResponse = (Map<String,Object>)serializer.fromJson(responseDetails,Object.class);
さらにGson fromJson
機能を使用してMap<String,Object>
にそれをデシリアライズ。
私の期待するところは:このアプローチでは、期待されるjsonを得るために、逆直列化されたjsonを繰り返し処理し、手動で作成する必要があります。
fromJsonの戻り値として、デシリアライズ処理中に応答jsonを取得する方法はありますか。すなわち
List<Map<String, String>> myResults = serializer.fromJson(responseDetails);
以下のように何か私たちはfromJson機能を無効にしてList<Map<String, String>>
を返す私たち自身のカスタムデシリアライザを書くことができます。
パフォーマンスを向上させるための提案やその他の方法が必要です。この後
RESTサービスのために、より明確化
のようなJavaコレクションストリームを使用して抽出することができます。まだ 'map'を使用して繰り返しています。 –