问题描述
我想基于通用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 (将#修改为@)