我的想法是,我想将JSON数组["foo", "bar"]
转换为Java对象,因此需要按索引将每个数组元素映射到属性。
假设我有以下JSON:
{
"persons": [
[
"John",
"Doe"
],
[
"Jane",
"Doe"
]
]
}
如您所见,每个人都只是一个数组,其中名字是索引为0的元素,姓氏是索引为1的元素。
我想反序列化为List<Person>
。我使用mapper如下:
mapper.getTypeFactory().constructCollectionType(List.class, Person.class)
在哪里Person.class
:
public class Person {
public final String firstName;
public final String lastName;
@JsonCreator
public Person(@JsonProperty() String firstName, @JsonProperty String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
我想知道是否可以以某种方式将数组索引指定为@JsonProperty
参数而不是键名?
感谢bureaquete建议使用自定义解串器。但它更适合我注册SimpleModule
而不是@JsonDeserialize
注释。下面是完整的JUnit测试示例:
@RunWith(JUnit4.class)
public class MapArrayToObjectTest {
private static ObjectMapper mapper;
@BeforeClass
public static void setUp() {
mapper = new ObjectMapper();
SimpleModule customModule = new SimpleModule("ExampleModule", new Version(0, 1, 0, null));
customModule.addDeserializer(Person.class, new PersonDeserializer());
mapper.registerModule(customModule);
}
@Test
public void wrapperDeserializationTest() throws IOException {
//language=JSON
final String inputJson = "{\"persons\": [[\"John\", \"Doe\"], [\"Jane\", \"Doe\"]]}";
PersonsListWrapper deserializedList = mapper.readValue(inputJson, PersonsListWrapper.class);
assertThat(deserializedList.persons.get(0).lastName, is(equalTo("Doe")));
assertThat(deserializedList.persons.get(1).firstName, is(equalTo("Jane")));
}
@Test
public void listDeserializationTest() throws IOException {
//language=JSON
final String inputJson = "[[\"John\", \"Doe\"], [\"Jane\", \"Doe\"]]";
List<Person> deserializedList = mapper.readValue(inputJson, mapper.getTypeFactory().constructCollectionType(List.class, Person.class));
assertThat(deserializedList.get(0).lastName, is(equalTo("Doe")));
assertThat(deserializedList.get(1).firstName, is(equalTo("Jane")));
}
}
class PersonsListWrapper {
public List<Person> persons;
}
class Person {
final String firstName;
final String lastName;
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
class PersonDeserializer extends JsonDeserializer<Person> {
@Override
public Person deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode node = jp.readValueAsTree();
return new Person(node.get(0).getTextValue(), node.get(1).getTextValue());
}
}
请注意,如果不需要包装器对象,则可以按如下所示[["John", "Doe"], ["Jane", "Doe"]]
直接List<Person>
使用映射器反序列化JSON数组:
List<Person> deserializedList = mapper.readValue(inputJson, mapper.getTypeFactory().constructCollectionType(List.class, Person.class));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句