5

サーバーから生成された次の応答を取得していますcakephp

 [
 {
  "id": "42389",
  "start": "0000-00-00",
  "end": "0000-00-00",
  "event_id": null,
  "trip_id": "5791",
  "location_id": "231552",
  "user_id": "105",
  "users_attending": "0",
  "user_local": "0",
  "Trip": {
   "name": "Asdas"
  },
  "Event": [],
  "Location": {
   "name": "South Melbourne"
  }
 },
 {
  "id": "42392",
  "start": "0000-00-00",
  "end": "0000-00-00",
  "event_id": "1218",
  "trip_id": "4772",
  "location_id": "271505",
  "user_id": "105",
  "users_attending": "3",
  "user_local": "50",
  "Trip": {
   "name": "trip by 1059200"
  },
  "Event": {
   "title": "SampleEvent 454",
   "id": "1218"
  },
  "Location": {
   "name": "Houston"
  }
 },
 .......
 ]

問題は、パーサーEventがオブジェクトを予期しているが、その場合nullは空の配列を受け取っているということです。

応答はによって自動生成されるためcakephp、サーバー側の多くの場所で変更する必要があります。

Eventジャクソンが空の配列の場合にプロパティを無視する簡単な方法はありますか?

編集:

1つの配列と他のオブジェクトという名前の2つのプロパティを試してみEventましたが、それも機能しませんでした。

4

3 に答える 3

2

Deserializer多くのオブジェクトに対してこのような応答を処理する必要があったため、最終的に、特定のに対してを返すジェネリッククラスの作成に進みましたclass

これが私が使ったものです

public class Deserializer<T> {

  public JsonDeserializer<T> getDeserializer(final Class<T> cls) {
      return new JsonDeserializer<T> (){

         @Override
         public T deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException {
            JsonNode node = jp.readValueAsTree();
            if (node.isObject()) {
              return new ObjectMapper().convertValue(node, cls);
            }
            return null;
         }
     };
}

}

于 2012-10-13T18:52:52.347 に答える
1

I think it makes sense to separate it, if types are incompatible.

The other option would have been to use a common super-type, which would mean java.lang.Object, and you would get either List (for JSON array) or Map (for JSON Object). But would need to do post-processing to bind into concrete types.

于 2012-10-02T21:21:05.003 に答える
0

この問題の最も簡単な解決策は、次の機能を追加することでした。

DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true

私のobjectmapperに。ジャクソンはあなたのために残りをします。https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.htmlを参照してください。

この回答は詳細な説明を提供します:https ://stackoverflow.com/a/22956168/9279756

于 2019-06-15T08:55:10.320 に答える