2017-01-06 12 views
2

私はAPIからいくつかのJsonを取得しようとしており、それらを処理するいくつかのPOJOに解析しますが、私は単純なStringまたはarrayList弦のジャクソンマッピング文字列または単純な文字列のリスト

{ 
    "offerDisplayCategoryMapping": [ 
    { 
     "offerKey": "EUICC_BASE_ACTIVATION_V01", 
     "categoriesKeys": { 
     "categoryKey": "Included" 
     } 
    }, 
    { 
     "offerKey": "EUICC_BASE_ACTIVATION_V02", 
     "categoriesKeys": { 
     "categoryKey": "Included" 
     } 
    }, 
    { 
     "offerKey": "EUICC_BASE_ACTIVATION_V03", 
     "categoriesKeys": { 
     "categoryKey": [ 
      "Option", 
      "Included" 
     ] 
     } 
    }] 
} 

私はAPIからの結果を得るために春の休憩を使用しています:

JSONは次のようになります。 categoriesKeysを表すPOJOを作成し、categoryKeyを定義し、RestTemplateを定義しました。ObjectMapperを定義しました。単純な文字列の場合はDeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAYを有効にしましたが、これは機能しません。

提案がありますか?

+0

あなたがあなたのPOJO(S)とのあなた 'RestTemplate'を追加する場合を助けるために容易になるだろう質問 –

答えて

6

、個々の特性上、これをサポートすることも可能である:

public class Container { 
    @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) 
    // ... could also add Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED 
    public List<String> tags; 
} 
2

キーのリストなので動作します。場合にはプロパティが単一の値を持っていないDeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY 以下のような配列で配列

{ 
    "CategoriesKeys":{ 
    "categoryKey":{ 
     "keys":"1" 
     } 
    } 
} 



@JsonRootName("CategoriesKeys") 
    protected static class CategoriesKeys{ 

     private CategoryKey categoryKey; 
//getters and setters 

} 

protected static class CategoryKey{ 

     private List<String> keys; 
//getters and setters 

} 

TestClass: 

ObjectMapper mapper=new ObjectMapper(); 
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); 
    mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); 
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 

Output: 

{"CategoriesKeys":{"categoryKey":{"keys":["1"]}}} 
3

として単一のプロパティをデシリアライズを保証します私は春の外にちょうどジャクソンでこれを試してみましたし、と期待どおりに動作するかどうか:

ObjectMapper mapper = new ObjectMapper(); 
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); 

マインドそのRestTemplate登録ObjectMapperそれ自身の持つMappingJacksonHttpMessageConverter。この設定方法はCheck this answerObjectMapperです。

すでに言及したグローバル構成に加えて
関連する問題