如何解决具有动态属性名称的Java中的JSON反序列化
我想基于通用Java类型反序列化JSON对象。 我有这些JSON字符串:
{
"data": {
"person": [
{
"name": "name1"
}
]
}
}
{
"data": {
"address": [
{
"line1": "line1"
}
]
}
}
我有Person
和Address
的相应类
如何定义JSON文件中要使用的属性?
public static class ResponseData<T> {
@JsonProperty("person") // todo make this dynamic depending on T
T[] entity;
}
全面测试(地址失败)
import static org.junit.jupiter.api.Assertions.*;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Data;
import org.junit.jupiter.api.Test;
class DeserializationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
String personJson = "{"
+ " \"data\": {"
+ " \"person\": ["
+ " {"
+ " \"name\": \"name1\""
+ " }"
+ " ]"
+ " }"
+ "}";
String addressJson = "{"
+ " \"data\": {"
+ " \"address\": ["
+ " {"
+ " \"line1\": \"line1\""
+ " }"
+ " ]"
+ " }"
+ "}";
@Test
void testDeserialization() throws JsonProcessingException {
Response<Person> personResponse = MAPPER.readValue(personJson,new TypeReference<Response<Person>>() { });
Person[] personEntityArray = personResponse.getData().getEntity();
assertNotNull(personEntityArray);
assertNotNull(personEntityArray[0]);
assertEquals("name1",personEntityArray[0].getName());
Response<Address> addressResponse = MAPPER.readValue(addressJson,new TypeReference<Response<Address>>() { });
Address[] addressEntityArray = addressResponse.getData().getEntity();
assertNotNull(addressEntityArray);
assertNotNull(addressEntityArray[0]);
assertEquals("line1",addressEntityArray[0].getLine1());
}
@Data
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Response<T> {
ResponseData<T> data;
}
@Data
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ResponseData<T> {
@JsonProperty("person") // todo make this dynamic depending on T
T[] entity;
}
@Data
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Person {
String name;
}
@Data
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Address {
String line1;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。