【问题标题】:POJO Object not converting to JSON ObjectPOJO 对象未转换为 JSON 对象
【发布时间】:2015-02-17 23:48:50
【问题描述】:

我正在尝试编写一个 REST 服务,该服务将获取二进制数据并返回 JSON 对象。

REST 服务:

public class FileUpload {

    @POST
    @Path("/upload")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    @Produces(MediaType.APPLICATION_JSON)
    public Result uploadFile(InputStream uploadedInputStream) {
        String uploadedFileLocation = "c://tomcatupload/" + filename;

        // save it
        writeToFile(uploadedInputStream, uploadedFileLocation);

        String output = "File uploaded to : " + uploadedFileLocation;

        //return Response.status(200).entity(output).build();
        Result result = new Result("status","success");

        return result;

    }
}

结果对象

import javax.xml.bind.annotation.XmlRootElement;

public class Result {
    private String Status;
    private String result;
    public Result(){

    }
    public Result(String status, String result){
        this.Status = status;
        this.result = result;
    }
    public String getStatus() {
        return Status;
    }
    public void setStatus(String status) {
        Status = status;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    @Override
    public String toString(){
        return new StringBuffer("result : ").append(this.result).toString();
    }

}


public class FileUploadClient {
    public static void main(String[] args) throws JSONException{
        Client client = Client.create();
        WebResource webResource = client
                   .resource("http://localhost:8080/RESTFileAttachmentService/rest/file/upload");
        String fileName = "C:/test.txt";
        InputStream fileInStream = null;
        try {
            fileInStream = new FileInputStream(fileName);
        } catch (FileNotFoundException e) {
            System.out.println("File not found exception");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //String sContentDisposition = "attachment; filename=\"" + fileName.getName()+"\"";
        //WebResource fileResource = a_client.resource(a_sUrl);
        System.out.println("Webservice is being called = " + fileInStream);
        ClientResponse response = webResource.type(MediaType.APPLICATION_OCTET_STREAM).accept("application/json")
                                .post(ClientResponse.class, fileInStream);
        System.out.println("Webservice call over = " + response.getStatus());
        System.out.println("Webservice call over = " + response.getEntity(Result.class));

    }
}

输出:

result : success

我不确定它为什么不将输出打印为 JSON 对象。这看起来像一个原始字符串。

直接打印 String.class 时出错 -

Exception in thread "main" javax.ws.rs.WebApplicationException: com.owlike.genson.JsonBindingException: Could not deserialize to type class java.lang.String
    at com.owlike.genson.ext.jaxrs.GensonJsonConverter.readFrom(GensonJsonConverter.java:127)
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:553)
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:506)
    at com.gsa.gov.file.upload.FileUploadClient.main(FileUploadClient.java:37)

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>esoa</groupId>
    <artifactId>RESTFileAttachmentService</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>RESTFileAttachmentService Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.8</version>

        </dependency>
        <!-- <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.0_spec</artifactId> 
            <version>1.0.2.Final</version> </dependency> -->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-bundle</artifactId>
            <version>1.18.1</version>
        </dependency>

        <dependency>
            <groupId>com.owlike</groupId>
            <artifactId>genson</artifactId>
            <version>0.99</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.9</version>
            <scope>provided</scope>
        </dependency>


    </dependencies>
    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <build>
        <finalName>RESTFileAttachmentService</finalName>
    </build>
</project>

【问题讨论】:

  • 你说的是 JSON,但你是用与 XML 相关的东西来注释它?
  • 我应该明确地添加引号来看起来像 JSON 对象还是应该自动发生转换?

标签: java json jersey


【解决方案1】:

尚未测试,但很可能是因为您正在打印 Result 对象,该对象将打印 toString。如果您想要原始 JSON,请使用 response.getEntity(String.class)。当您使用 getEntity(Result.class) 时,原始 JSON 将转换为 Result 对象。

【讨论】:

  • 您可能是对的,但是当我显示字符串时出现不同的错误。我已经给出了错误。
  • 我不(或从未真正)使用 Genson 作为提供者。你能发布 Maven 依赖项吗?另外,如果需要以任何方式配置 Genson,您能否发布这些配置,以便我进行测试。似乎是 Genson 的问题,因为我在使用普通 JSON 提供程序时从来没有遇到过任何问题
  • 如果我不使用 Genson,我会得到一个不同的错误,即;它无法写入 JSON 响应。
  • this answer 的底部附近。您已经拥有jersey-json 提供程序,但还需要其他一些配置。然后注释掉所有 Genson 的东西。我不确定它是否会自动注册(不希望它发生冲突)
  • 服务器端可以使用web.xml或者程序化配置(主要是开启pojo映射功能)。对于客户端,如果您想映射回Result,也需要这样做。如果您只想要使用 getEntity(String.class) 的原始 JSON,则无需在客户端启用此功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多