我正在尝试使用gson.fromJson反序列化使用postman发送的对象。
@POST
@Path( "company" ) // takes name as a path parameter
@Produces( "application/json" ) // response formatted as JSON
public Response insertCompany(String content) {
Gson gson = new Gson();
CompanyWithNoIdReturn newCompany = gson.fromJson(content, CompanyWithNoIdReturn.class);
}
public class CompanyWithNoIdReturn {
private final String name;
private final String description;
private final String logo;
public CompanyWithNoIdReturn(String name, String description, String logo)
{
this.name = name;
this.description = description;
this.logo = logo;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getLogo() {
return logo;
}
}
出现的错误是:javax.servlet.ServletException:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:预期为BEGIN_OBJECT但是为STRING 在第1行第1列
我理解这意味着它希望它以{
开头,而不是here中提到的"
。虽然我没有理解的是我如何解决它?
编辑:使用表单 - 数据时,内容如下:
content = (java.lang.String) "------WebKitFormBoundaryUG5yy1gW9G2V5qcz
Content-Disposition: form-data; name="CompanyName"
newCompanyName2
------WebKitFormBoundaryUG5yy1gW9G2V5qcz
Content-Disposition: form-data; name="Description"
newDescription2
------WebKitFormBoundaryUG5yy1gW9G2V5qcz
Content-Disposition: form-data; name="logo"
newLogo2
------WebKitFormBoundaryUG5yy1gW9G2V5qcz--
"
答案 0 :(得分:0)
我认为你期望JSON格式的body(内容变量)。但根据你的邮递员形象,你发送form-data
。
尝试切换到raw
并插入此内容:
{
"name": "Company name",
"description": "Company description",
"logo": "logo"
}
答案 1 :(得分:0)
如果您想使用JaxRs服务处理表单数据,您应该查看@FormParam。您的服务将成为
@POST
@Path( "company" ) // takes name as a path parameter
@Produces( "application/json" ) // response formatted as JSON
public Response insertCompany(@FormParam("CompanyName") String name, @FormParam("Description") String description, @FormParam("Logo") String logo) ) {
CompanyWithNoIdReturn newCompany = new CompanyWithNoIdReturn(name, description, logo);
return Response.ok(newCompany).build();
}
您必须确保FormParam注释中指定的名称与表单中的字段名匹配。