提问者:小点点

雷斯特模板自定义杰克逊JSON反序列化器


我得到了一个JSON的回答,看起来像这样:

[{"name":"this" }, { "name":"that"}]

我宁愿不为此创建一个POJO(接收一个POJO数组),而是只获取一个带有值的字符串数组。那么我如何指示杰克逊这样做,然后将其与RestTemplate一起使用呢?


共2个答案

匿名用户

只需将List指定为目标Class,jackson将使用List和Map编写相当于JSONArray和JSONObject的内容

    final ObjectMapper mapper = new ObjectMapper ();
    try
    {
        final List readValue = mapper.readValue ("[{ 'name': 'This' }, { 'name': 'That' }]".replace ('\'', '"'), List.class);
        //readValue is a list of Map
    }
    catch (final IOException e)
    {
        e.printStackTrace();
    }

匿名用户

你可以试试这个:

ParameterizedTypeReference<List<HashMap<String, String>>> typeRef = new ParameterizedTypeReference<List<HashMap<String, String>>>() {};
ResponseEntity<List<HashMap<String, String>>> response = new RestTemplate().exchange(youUrl, HttpMethod.GET, null, typeRef);