有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中动态属性名的JSON反序列化

我想基于通用Java类型反序列化JSON对象。 我有这些JSON字符串:

{
  "data": {
    "person": [
      {
        "name": "name1"
      }
    ]
  }
} 
{
  "data": {
    "address": [
      {
        "line1": "line1"
      }
    ]
  }
}

我有PersonAddress的相应类

如何从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;
  }

}

共 (0) 个答案