Java 解析 json 字符串时无法识别的字段,未标记为可忽略

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19173640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:44:48  来源:igfitidea点击:

Unrecognized field , not marked as ignorable ,when parsing json string

javajsonweb-servicesjaxbjersey

提问by jos

I am working on a Jersey rest services. trying to pass a generic object(in my case AppObject)as post request and the response from the server is also the generic object(in my case AppObject)i am expecting a string {"license":"12345","list":[{"alternateId":"AlternateID","classificati??on":"1"}] }but insted of listi am getting dimRequirementas shown below. So when parsing the json am getting the exception. Is there a way to get it as list itself with out changing the code. Or any alternative could anybody help me.

我正在从事泽西岛的休息服务。尝试将通用对象(在我的情况下为 AppObject)作为发布请求传递,并且来自服务器的响应也是通用对象(在我的情况下为 AppObject)我期待一个字符串{"license":"12345","list":[{"alternateId":"AlternateID","classificati??on":"1"}] }插入列表我得到如下所示的dimRequirement。因此,在解析 json 时出现异常。有没有办法在不更改代码的情况下将其作为列表本身。或者任何其他人都可以帮助我。

Json string receiving at the client

客户端接收 Json 字符串

{"license":"12345","dimRequirement":[{"alternateId":"AlternateID","classificati??on":"1"}] }

my client

我的客户

AppObject<DimRequirement> appObject = new AppObject<DimRequirement>();
        appObject.setClientKey(4L);
        Client client = Client.create();
        WebResource webResource = client
                   .resource("http://localhost:8080/myproject/");

        JSONObject json = new JSONObject(appObject);
        ClientResponse response = webResource.path("rest").path("requirement/getreq").type("application/json").accept("application/json")
                .post(ClientResponse.class,json.toString());
        String output = response.getEntity(String.class);
        System.out.println(output);
        appObject= new ObjectMapper().readValue(
                output, AppObject.class);

error

错误

   Unrecognized field "dimRequirement" (Class com.vxl.AppObject), not marked as ignorable
at [Source: java.io.StringReader@7be6f06c; line: 1, column: 49] (through reference chain: com.vxl.appanalytix.AppObject["dimRequirement"])
    at org.codehaus.Hymanson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)
    at org.codehaus.Hymanson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:244)
    at org.codehaus.Hymanson.map.deser.StdDeserializer.reportUnknownProperty(StdDeserializer.java:589)
    at org.codehaus.Hymanson.map.deser.StdDeserializer.handleUnknownProperty(StdDeserializer.java:575)
    at org.codehaus.Hymanson.map.deser.BeanDeserializer.handleUnknownProperty(BeanDeserializer.java:684)
    at org.codehaus.Hymanson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:515)
    at org.codehaus.Hymanson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:351)
    at org.codehaus.Hymanson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2131)
    at org.codehaus.Hymanson.map.ObjectMapper.readValue(ObjectMapper.java:1402)
    at com.vxl.CheckJersy.main(CheckJersy.java:56)

Generic Class

通用类

@XmlRootElement
@XmlSeeAlso({DimRequirement.class })
public class AppObject<T> implements Serializable {

    private List<T> list;
    private Long clientKey;

    public AppObject() {
        list = new ArrayList<T>();

    }

    public AppObject(List<T> list) {
        this.list = list;
    }

    @XmlAnyElement(lax = true)
    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public Long getClientKey() {
    return clientKey;
}

public void setClientKey(Long clientKey) {
    this.clientKey = clientKey;
}

}

service

服务

@Path("/requirement")
public class DimRequirementManagerImpl {
@POST
    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/getreq")
    @Override
    public AppObject getAllByClientNIsCurrent(
            AppObject<DimRequirement> appObj) {
        List<DimRequirement> dimreqlist = dimRequirementDao
                .getAllByClientNIsCurrent(appObj.getClientKey());
        AppObject appObject = new AppObject();
        appObject.setList(dimreqlist);
        return appObject;
    }}

DimRequirement which is setting to AppObject

DimRequirement 设置为 AppObject

@XmlRootElement
public class DimRequirement extends BaseObject implements Serializable {
private Long requirementKey;
private String description;
private String priority;
@Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="requirementKey")
    public Long getRequirementKey() {
        return this.requirementKey;
    }    
    public void setRequirementKey(Long requirementKey) {
        this.requirementKey = requirementKey;
    }
 @Column(name="Description") 
    public String getDescription() {
        return this.description;
    }    
    public void setDescription(String description) {
        this.description = description;
    }
 @Column(name="Priority") 
    public String getPriority() {
        return this.priority;
    }    
    public void setPriority(String priority) {
        this.priority = priority;
    }
}

采纳答案by jos

i have changed the return type of service to string(json string).

我已将服务的返回类型更改为字符串(json 字符串)。

service

服务

@Path("/requirement")
public class DimRequirementManagerImpl {
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/getreq")
@Override
public String getAllByClientNIsCurrent(AppObject<DimRequirement> appObj) {
try {
     List<DimRequirement> dimreqlist = dimRequirementDao.getAllByClientNIsCurrent(appObj.getClientKey());
     AppObject appObject = new AppObject();
     appObject.setList(dimreqlist);
     JSONObject jsonget = new JSONObject(appObject);
     return jsonget.toString();
     }catch (Exception e) {
        AppObject<DimRequirement> appObject = new AppObject<DimRequirement>();
        appObject.setLicense("12345");
        JSONObject jsonget = new JSONObject(appObject);
        return jsonget.toString();
    }
}}

this worked for the same client in the question returnig json {"license":"12345","list":[{"alternateId":"AlternateID","classificati??on":"1"}] }

这适用于问题 returnig json {"license":"12345","list":[{"alternateId":"AlternateID","classificati??on":"1"}] }

client

客户

 AppObject<DimRequirement> appObject = new AppObject<DimRequirement>();
        appObject.setClientKey(4L);
        Client client = Client.create();
        WebResource webResource = client
                   .resource("http://localhost:8080/myproject/");

        JSONObject json = new JSONObject(appObject);
        ClientResponse response = webResource.path("rest").path("requirement/getreq").type("application/json").accept("application/json")
                .post(ClientResponse.class,json.toString());
        String output = response.getEntity(String.class);
       AppObject<DimRequirement> appObjectclientns = new ObjectMapper()
                .readValue(output,
                        new TypeReference<AppObject<DimRequirement>>() {
                        });