2017-07-03 20 views
0

以下に示すように重複キーを持つJSONがあります。重複キーを持つJSONをマルチマップとして表示

{ 
     "name": "Test", 
     "attributes": [{ 
      "attributeName": "One", 
      "attributeName": "Two", 
      "attributeName": "Three" 
     }] 
    } 

私はジャクソンを使用してMap<String, Object>にそれを変換すると下図のように、それが変換されます。

{名前=テスト=属性[{たattributeName =三}]}

属性名の最後に出現の値が考慮されます。代わりにMultimapとしてそれを表すようにジャクソンに伝える方法はありますか?私はMultimapの実装を使用しても構いません。下図のように私の現在のコードは次のとおりです。

import java.util.HashMap; 
import java.util.Map; 

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

public class TestJSON { 

    public static void main(String[] args) throws Exception{ 
     ObjectMapper mapper = new ObjectMapper(); 
     String json = "{\"name\": \"Test\",\"attributes\": [{\"attributeName\": \"One\",\"attributeName\": \"Two\",\"attributeName\": \"Three\"}]}"; 
     Map<String, Object> map = new HashMap<>(); 
     map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){}); 
     System.out.println(map); 
    } 

} 
+0

JSONを修正して有効にする方法はありますか? https://stackoverflow.com/questions/5306741/do-json-keys-need-to-be-uniqueを参照してください –

答えて

0

は、ジャクソンは彼の母国方法でそれを処理することを考えてはいけない、しかし、あなたは、単純なPOJOに、このJSONをラップし、そこからMultimapはを得ることができます。例:

public class Attribute { 
    private String attributeName; 

    // getter and setter here 
} 

public class AttributeContainer { 
    private String name; 
    private List<Attribute> attributes; 

    public Multimap<String, String> getAttributeMultiMap() { 
     ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder(); 
      for (Attribute attribute : attributes) { 
      builder.put("attributeName", attribute.getAttributeName()) 
      } 
     return builder.build(); 
    } 

    // getters and setters here 
} 

public void main(String[] args) { 
    ObjectMapper mapper = new ObjectMapper(); 
    String json = "{\"name\": \"Test\",\"attributes\": [{\"attributeName\": \"One\",\"attributeName\": \"Two\",\"attributeName\": \"Three\"}]}"; 
    AttributeContainer attributeContainer; 
    attributeContainer = mapper.readValue(json, new TypeReference<AttributeContainer>(){}); 

    System.out.println(attributeContainer.getAttributeMultiMap()); 
} 
+0

使用しているマルチマップの実装を知っていますか? – Beginner

+0

確かに、[guava](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/ImmutableMultimap.html#builder()) – rxn1d

+0

問題がありますMultimapを構築する際に使用します。使用しているguavaのバージョンを知ることができますか? – Beginner

関連する問題