【问题标题】:Unmarshal a Json Array in a Json List在 Json 列表中解组 Json 数组
【发布时间】:2018-01-10 16:36:57
【问题描述】:

我需要获取所有电影的列表。

我处于这种情况,我不知道如何管理它。 我的项目分为两个较小的项目。后端项目和前端项目。 生成包含电影列表的 Json 的后端部分。

服务有这种模式

@GET
@Produce(json)  // here is a particular library and it funcion correctly.
List<Film> getAllFilms

调用此服务的输出具有以下模式:

[{"title:abc","time": 5486448}, {....}, {....}]

在前端项目中,我使用的是 Resteasy 。 我创建了一个类服务来调用后端并管理响应

    List<Film> film= new ArrayList<>();
    try{
    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target("http://localhost:8080/film");


    Response response = target.request().get();
    film=  List<Film>) response.readEntity(Film.class);

我有这种类型的例外:

javax.ws.rs.ProcessingException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of FILM out of START_ARRAY token

现在我正在尝试理解一些东西,但是里面有很多材料,我正在四处游荡。 如何将数组解组为列表?

【问题讨论】:

    标签: java json rest resteasy


    【解决方案1】:

    您可以使用jackson的readValue方法将其转换为List

    public List<Film> convert(String jsonString) throws JsonParseException, JsonMappingException,
                IOException {
    
            ObjectMapper objectMapper = new ObjectMapper();
    
            List<Film> filmList = objectMapper.readValue(
                    jsonString,
                    objectMapper.getTypeFactory().constructCollectionType(
                            List.class, Film.class));
    
       return filmList;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-11
      • 2021-09-06
      • 1970-01-01
      • 2017-11-26
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      相关资源
      最近更新 更多