我有一个带有重复键的JSON,如下所示。
{
"name": "Test",
"attributes": [{
"attributeName": "One",
"attributeName": "Two",
"attributeName": "Three"
}]
}
当我使用杰克逊将其转换为Map<String, Object>
时,它会如下所示进行转换。
{name = Test,attributes = [{attributeName = Three}]}
考虑最后一次出现的属性名称的值。有没有办法告诉杰克逊将其表示为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 :(得分:0)
不要认为Jackson会以他的本地方式处理它,但是你可以将这个JSON包装成简单的POJO并从中获取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());
}