【问题标题】:How to convert to json to object by passing the object type如何通过传递对象类型将json转换为对象
【发布时间】:2019-12-17 14:22:51
【问题描述】:
 public static Object convertToObject(String json) {
    validate("json", json);
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(json, new TypeReference<Object>(){});
    } catch (JsonProcessingException ex) {
        throw new RuntimeException("Failed to convert json to object: "+json, ex);
    }
 }

//Here I'm doing type cast for the returned object
  Map<String, ArrayList<Integer>> convertedMap = (Map<String, ArrayList<Integer>>) RestClient.convertToObject(json);

我试过上面的代码 我正在使用杰克逊,我需要传递带有类型的 json,这样我就可以避免在调用者位置进行类型转换。

谁能帮我解决这个问题?

提前致谢

【问题讨论】:

    标签: java json generics casting


    【解决方案1】:

    对象映射器需要Class 类型的第二个参数,所以尝试传递:

    Object.class
    

    如下:

    return mapper.readValue(json, Object.class);
    

    【讨论】:

      【解决方案2】:

      首先,您应该在公共类中使用此方法进行 Mapper 初始化

      public static ObjectMapper getJacksonMapper() {
          ObjectMapper mapper = new ObjectMapper();
          mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
          mapper.enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
          mapper.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
          return mapper;
      }
      

      第二件事,你应该为相应的json创建POJO类。最后你可以得到json字符串必须转换为POJO类,你可以很容易地使用它。

      SamplePOJO poListResponse = AppUtils.getJacksonMapper().readValue(jsonString, SamplePOJO.class);
      

      【讨论】:

        猜你喜欢
        • 2021-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多