我正在和杰克逊一起使用Spring Boot。我有一个不寻常的JSON集来自Elasticsearch(spring-data-elasticsearch),我需要读入POJO。
{
"thread_name":"main",
"sort":[
1522270372773,
"log#AWJuYn7SAKReCIGzMYda"
]
}
值得注意的是,“sort”数组包含一个数字,然后是一个String。我没有运气为此正确地制作Java pojo。正确的方法是将“排序”声明为对象数组吗?然后构造函数是什么样的?
更新6/12/18:
根据要求添加一些额外的代码:
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import com.fasterxml.jackson.annotation.JsonProperty;
@Document(indexName = "logstash-*", type="log")
public class LogEntry {
@Id
private String id;
@JsonProperty("level")
private String level;
@JsonProperty("level_value")
private Integer levelValue;
@JsonProperty("host")
private String host;
@JsonProperty("cluster")
private String cluster;
@Field(type = FieldType.Nested)
@JsonProperty("@timestamp")
private String timestamp;
private String message;
@JsonProperty("application_name")
private String applicationName;
@JsonProperty("application_version")
private String applicationVersion;
@JsonProperty("thread_name")
private String threadName;
@JsonProperty("stack_trace")
private String stackTrace;
@JsonProperty("logger_name")
private String loggerName;
@JsonProperty("sort")
private List<Object> sort;
<truncated generic getters/setters>
}
这是重现null的驱动程序:
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.perspectium.elasticsearch.entities.LogEntry;
public class Test {
private static String RESPONSE = "{\n" +
" \"@timestamp\": \"2018-03-28T20:52:52.773Z\",\n" +
" \"application_name\": \"bleah-server\",\n" +
" \"level_value\": 400,\n" +
" \"thread_name\": \"main\",\n" +
" \"host\": \"df58952e2cb9\",\n" +
" \"logger_name\": \"com.bleah.Manager\",\n" +
" \"application_version\": \"7.77.0-SNAPSHOT\"\n" +
" },\n" +
" \"sort\": [\n" +
" 1522270372773,\n" +
" \"log#AWJuYn7SAKReCIGzMYda\"\n" +
" ]\n" +
" }";
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
System.out.println("Start");
ObjectMapper objectMapper = new ObjectMapper();
LogEntry logEntry = objectMapper.readValue(RESPONSE.getBytes(), LogEntry.class);
System.out.println(objectMapper.writeValueAsString(logEntry));
System.out.println("Finish.");
}
}