没有为响应类型找到合适的HttpMessageConverter - Custom RestTemplate

时间:2015-09-16 19:21:01

标签: java android spring rest

首先,抱歉可能重复。我发现了一些有关类似问题的问题。但是,我仍然无法弄清楚我的具体情况是什么。

所以,来自服务器的示例json:

[
  {
    "_id": "55f9690f30ef6f210e2dc3a5",
    "ID": "74c4bf82-9f78-4df5-b9d7-6547e2a55eaa",
    "Name": "myLand, Saarbrücken",
    "__v": 0,
    "Shops": [
      {
        "ID": "b8eacee1-b2c6-48aa-ac6f-2e7fbe3a5d68",
        "Name": "ARA",
        "_id": "55f9690f30ef6f210e2dc3a6",
        "News": [
          {
            "ID": "d79b7f51-7d5c-4bd6-9321-e40c6e93788c",
            "ValidFrom": "2015-01-08T00:00:00",
            "ValidTo": "2015-09-30T00:00:00",
            "_id": "55f9690f30ef6f210e2dc3a7",
            "Texts": [
              {
                "ID": "TITLE",
                "Value": "11. Wochenspiegel Firmenlauf",
                "_id": "55f9690f30ef6f210e2dc3a9"
              },
              {
                "ID": "BODY",
                "Value": "Wir gratulieren zur ersten und gleich sehr erfolgreichen Teilnahme am 11.Wochenspiegel Firmenlauf in Dillingen,\r\nunsere Teams vom “Outlet center Wadgassen“ haben ihren Lauf mit tollen Zeiten abgeschlossen und hatten trotz\r\nhohen Temperaturen einen wunderbaren Tag – wie man sehen kann. Wir freuen uns schon jetzt auf nächstes Jahr!",
                "_id": "55f9690f30ef6f210e2dc3a8"
              }
            ]
          }
        ],
        "Texts": [
          {
            "ID": "DESCRIPTION",
            "Value": "Mit Tradition in die Zukunft Seit sechs Jahrzehnten steht ara für vielfältige Schuhmode erstklassiger Qualität,",
            "_id": "55f9690f30ef6f210e2dc3aa"
          }
        ]
      }
    ]
  }
]

我生成了一个名为Mall的类(以及其余数据结构的所有子类):

public class Mall
{

    private String Id;
    private String ID;
    private String Name;
    private int V;
    private List<Shop> Shops = new ArrayList<Shop>();
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * @return The Id
     */
    public String getId()
    {
        return Id;
    }

    /**
     * @param Id The _id
     */
    public void setId(String Id)
    {
        this.Id = Id;
    }

    /**
     * @return The ID
     */
    public String getID()
    {
        return ID;
    }

    /**
     * @param ID The ID
     */
    public void setID(String ID)
    {
        this.ID = ID;
    }

    /**
     * @return The Name
     */
    public String getName()
    {
        return Name;
    }

    /**
     * @param Name The Name
     */
    public void setName(String Name)
    {
        this.Name = Name;
    }

    /**
     * @return The V
     */
    public int getV()
    {
        return V;
    }

    /**
     * @param V The __v
     */
    public void setV(int V)
    {
        this.V = V;
    }

    /**
     * @return The Shops
     */
    public List<Shop> getShops()
    {
        return Shops;
    }

    /**
     * @param Shops The Shops
     */
    public void setShops(List<Shop> Shops)
    {
        this.Shops = Shops;
    }

    public Map<String, Object> getAdditionalProperties()
    {
        return this.additionalProperties;
    }

    public void setAdditionalProperty(String name, Object value)
    {
        this.additionalProperties.put(name, value);
    }

}

服务器返回conent-type text / plain。要修改内容类型,我编写了简单的扩展类:

public class RestTemplateJSON extends RestTemplate
{

    @Override
    protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
                              ResponseExtractor<T> responseExtractor) throws RestClientException
    {

        //logger.info(RestTemplateJSON.class.getSuperclass().getSimpleName() + ".doExecute() is overridden");

        Assert.notNull(url, "'url' must not be null");
        Assert.notNull(method, "'method' must not be null");
        ClientHttpResponse response = null;
        try
        {
            ClientHttpRequest request = createRequest(url, method);
            if (requestCallback != null)
            {
                requestCallback.doWithRequest(request);
            }
            response = request.execute();

            // Set ContentType to JSON
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

            if (!getErrorHandler().hasError(response))
            {
                logResponseStatus(method, url, response);
            } else
            {
                handleResponseError(method, url, response);
            }
            if (responseExtractor != null)
            {
                return responseExtractor.extractData(response);
            } else
            {
                return null;
            }
        }
        catch (IOException ex)
        {
            throw new ResourceAccessException("I/O error on " + method.name() +
                    " request for \"" + url + "\":" + ex.getMessage(), ex);
        }
        finally
        {
            if (response != null)
            {
                response.close();
            }
        }

    }

    private void logResponseStatus(HttpMethod method, URI url, ClientHttpResponse response)
    {
        //if (logger.isDebugEnabled())
        {
            try
            {
                System.out.println(method.name() + " request for \"" + url + "\" resulted in " +
                        response.getRawStatusCode() + " (" + response.getStatusText() + ")");
            }
            catch (IOException e)
            {
                // ignore
            }
        }
    }

    private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException
    {
        getErrorHandler().handleError(response);
    }
}

最后,这就是我尝试使用我的网络服务的方式:

RestTemplateJSON restTemplate = new RestTemplateJSON();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Mall mall = restTemplate.getForObject(url, Mall.class);

但是,我仍然得到同样的例外:

  

无法提取回复:找不到合适的HttpMessageConverter   响应类型[m.m.restspringtest.Mall.Mall]和内容类型   [应用/ JSON]

据我所知,如果我更改内容类型,它应该没问题。你能告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:3)

所以,我终于明白了。在json中有数组,所以我想将它映射到Mall [],而不是Mall。我提供了错误的课程,应该有:

RestTemplateJSON restTemplate = new RestTemplateJSON();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Mall[] malls = restTemplate.getForObject(url, Mall[].class);