2016-11-16 12 views
0

私は次のコードスニペットを実行します。jacksonはデフォルトでリストをArrayListに逆シリアル化しますか?

import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.core.type.TypeReference; 
import com.fasterxml.jackson.databind.ObjectMapper; 

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.LinkedList; 
import java.util.List; 

public class JsonMapper { 
    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); 

    public static <T> String toJson(final T object) throws JsonProcessingException { 
     return OBJECT_MAPPER.writeValueAsString(object); 
    } 

    public static <T> T fromJson(final String json, final Class<T> clazz) throws IOException { 
     return OBJECT_MAPPER.readValue(json, clazz); 
    } 

    public static <T> T fromJson(final String json, final TypeReference<T> type) throws IOException { 
     return OBJECT_MAPPER.readValue(json, type); 
    } 
    public static void main(String args[]) throws IOException { 
     String json = "[1,2,3]"; 
     // TEST1: initialize TypeReference with type ArrayList 
     List<Integer> expected = JsonMapper.fromJson(json, new TypeReference<ArrayList<Integer>>(){}); 
     System.out.println(expected.getClass().getName()); 
     // TEST2: initialize TypeReference with type List 
     expected = JsonMapper.fromJson(json, new TypeReference<List<Integer>>(){}); 
     System.out.println(expected.getClass().getName()); 
     // TEST3: initialize TypeReference with type LinkedList 
     expected = JsonMapper.fromJson(json, new TypeReference<LinkedList<Integer>>(){}); 
     System.out.println(expected.getClass().getName()); 

    } 
} 

出力は次のとおりです。

java.util.ArrayList 
java.util.ArrayList 
java.util.LinkedList 

私はタイプArrayListまたはListTypeReferenceを初期化する際に、変数expectedのタイプはArrayListですが、私ならば、それはLinkedListなりタイプLinkedListTypeReferenceを初期化します。だから、jacksonは文字列リストをデフォルトでArrayListにデシリアライズしますか?

+0

さて、あなたはそのインターフェイス –

+0

ああの具体的な実装せずに '新しいList'を作ることができない、私は申し訳ありませんが、私はあなたのポイントを得ることはありません。より簡単に説明できますか? – expoter

+0

'java.util.List'はインタフェースです。クラスのインスタンスを持つことはできません –

答えて

1

はい、jacksonはデフォルトでArrayListに文字列リストを逆シリアル化します。コードはcom.fasterxml.jackson.databind.deser.impl.CreatorCollectorクラスである:

@Override 
    public Object createUsingDefault(DeserializationContext ctxt) throws IOException { 
     switch (_type) { 
     case TYPE_COLLECTION: return new ArrayList<Object>(); 
     case TYPE_MAP: return new LinkedHashMap<String,Object>(); 
     case TYPE_HASH_MAP: return new HashMap<String,Object>(); 
     } 
     throw new IllegalStateException("Unknown type "+_type); 
    } 
+0

これは、 'LinkedList'のケースにどのように対処していますか? –

+0

'TypeReference'が' LinkedList'のような具象型で初期化されていれば、 'createUsingDefault'メソッドは呼び出されません。 – expoter

+0

使用されているデフォルトの配列タイプをどのようにカスタマイズできますか? – singularity

関連する問題