我有一个名为Container的POJO,我想将其发送到RESTful Web服务。

客户端:

    try {

       JAXBContext ctx = JAXBContextFactory.createContext(new Class[] {Container.class}, null);
       jsonContent = objectToJSON(ctx, cont);
       HttpEntity entity = new ByteArrayEntity(jsonContent.getBytes("UTF-8"));
       ((HttpPost) httpUriRequest).setEntity(entity);

    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

     public String objectToJSON(JAXBContext ctx, Object object)
            {
                try
                {
                    Marshaller marshaller = ctx.createMarshaller();

                    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
                    marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);

                    StringWriter sw = new StringWriter();
                    marshaller.marshal(object, sw);

                    return sw.toString();
                }
                catch (JAXBException e){

                    System.out.println("--------JAXB EXCEPTION------------\n" );
                    e.printStackTrace();
                    LOGGER.error("JAXB marshalling error!", e);
                }
                return "HELLO";
            }


我正在使用REST-easy。

服务器端

@POST

    @Consumes({"application/json"})
    @Produces({"application/json"})
    public String handlePostRequest(Object resource) {

       System.out.println("\nINSIDE HANDLE POST: CONTENT CLASS" + resource.getClass());
       System.out.println("\nINSIDE HANDLE POST: " + resource);
        return "SIDD";
    }


在这里,我收到以Object类型发送的内容:
 public String handlePostRequest(Object resource) {

因此,SOP将类打印为LinkedHashMap,并将我的POJO(Container)的属性在HashMap中设置为键值对。

这里我想使用Object类型,因为从客户端发送的POJO在请求之间可能有所不同。所以我想写一个泛型函数。

现在,是否存在将LinkedHashMap(作为对象)转换为Java中的POJO的标准方法?

最佳答案

您可以将地图对象包装在POJO中,如下所示:

@Getter
@Setter
public class MyResource {
  @JsonProperty("map")
  private Map<Integer,Object> map;  // or LinkedHashMap if you want

  // You can have other fields here
}


您的方法签名如下所示:

@POST
@Consumes("application/json")
@Produces("application/json")
public String handlePostRequest(MyResource resource) {
   // Access your map
   resource.getMap();
}


JacksonJaxbJsonProvider为您进行编组和解组。 RESTful服务的输入如下所示:

{
"map": {
    "1" : "Hello",
    "2" : "World",
    ...
  }
}

关于java - 将LinkedHashmap转换为POJO?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33867322/

10-14 05:07