使用Jackson解析响应

时间:2018-05-11 21:57:41

标签: java jackson jaxb jaxb2 jackson-databind

我正在尝试使用Jackson解析api响应。得到像com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException这样的错误:无法识别的字段"健康"

我尝试过像

这样的选项
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); //with true

我认为简单的错误但无法弄明白。请帮忙

回应json:

{
  "Health": {
    "id": "abc_Server",
    "name": "ABC Request Service",
    "status": "GREEN",
    "dependencies": [
      {
        "id": "DB",
        "name": "MySQL",
        "message": "Connection successful.",
        "status": "GREEN"
      }
    ]
  }
}

java pojos

@JsonRootName(value = "Health")
public class HealthResponse {

  private String id;
  private String name;
  private String status;
  private List<Dependencies> dependencies;

  //getter and setter methods
  }
}


public class Dependencies {

  private String id;
  private String name;
  private String message;
  private String status;
  //getter and setter methods
}

主要课程:

ObjectMapper objectMapper = new ObjectMapper();
try {
InputStream response = healthCheckWebTarget.request(MediaType.APPLICATION_JSON).get(InputStream.class);
HealthResponse healthResponse = objectMapper.readValue(response, HealthResponse.class);
}catch(Exception e){
  //
}

还试过有一个pojo但没有工作

@JsonRootName(value = "Health")
public class Health {

  private HealthResponse health;

 //getter and setter
}

1 个答案:

答案 0 :(得分:0)

将JSON转换为Java对象时,实际上是反序列化,而不是序列化。所以使用这个:

objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); 

目前正在为我工​​作的完整代码(打印abc_Server):

    String json="{\"Health\":{\"id\":\"abc_Server\",\"name\":\"ABCRequestService\",\"status\":\"GREEN\",\"dependencies\":[{\"id\":\"DB\",\"name\":\"MySQL\",\"message\":\"Connectionsuccessful.\",\"status\":\"GREEN\"}]}}";

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    try {
        HealthResponse healthResponse = objectMapper.readValue(json, HealthResponse.class);
        System.out.println(healthResponse.getId());
    } catch (Exception e) {
        e.printStackTrace();
    }

HealthResponse

@JsonRootName(value = "Health")
class HealthResponse {
    [...]
}

Dependencies

没有变化

UNWRAP_ROOT_VALUE的文档。