【问题标题】:Not getting right JSON of the when returning list返回列表时没有得到正确的 JSON
【发布时间】:2013-02-20 16:53:07
【问题描述】:

以下是我用于以 JSON 形式返回模型列表的方法

    @RequestMapping(value = "/fetchAddress.htm", method = RequestMethod.GET)
@ResponseBody   
public  GenericEntity<List<Address>> fetchAddress(@RequestParam(value="addressId", required=true) int addressId){   
    logger.debug("fetchQueryDetails called");
    List<Address> al =queryDao.fetchAddress(addressId);

    GenericEntity<List<Address>> gal= new GenericEntity<List<Address>>(al){};   
    return gal;      
}

}

以下是我的模型类

    @XmlRootElement(name = "Address")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class AddressImpl implements Address {
     properties, setter, getter.
    }

以下是我得到的 JSON 响应

    {"rawType":"java.util.ArrayList","type":{"actualTypeArguments":["com.mvp.Address"],"rawType":"java.util.List","ownerType":null},"entity":[{"flatno":"S-2","houseNo":"42","street":"mother dairy","sector":"sec-2A","city":"kashi","state":"U.P.","country":"India","pin":"200001"},{"flatno":"S-2222222","houseNo":"42","street":"mother dairrrrrrrry","sector":"sec-2AAaa","city":"varansi","state":"U.P.","country":"India","pin":"201101"}]}

现在在 JSON 响应中,我不希望输出中的 rawType、type、ownerType 以及实体名称被更改,例如 addressList。还有任何想法如何避免 bean 类的某些属性不出现在 JSON 中。我正在使用 Jackson 库来创建 JSON。以下是我正在使用的罐子。

     jackson-mapper-asl-1.9.2.jar,
     jackson-xc-1.9.2.jar,
     jackson-jaxrs-1.9.2.jar,
     jackson-core-asl-1.9.2.jar

谁遇到过同样的情况,请指教。

谢谢

【问题讨论】:

    标签: java json spring jackson


    【解决方案1】:

    您可以使用注解@JsonProperty 自定义名称:

    @JsonProperty("NameOfProperty")
    public String getProperty() {
        return property;
    }
    

    如果您不需要属性,请使用:@JsonIgnoreProperties 忽略它

    @JsonIgnoreProperties
    public String getPropertyToExclude() {
        return propertyToExclude;
    }
    

    【讨论】:

    • 谢谢伯努瓦。我能够忽略 JSON 中不需要的属性。然而,除了返回对象列表之外,我仍然得到那些原始类型和所有我不想要的。另外我知道我可以更改 JSON 输出中的属性名称。但是我如何命名列表。由于defualt 即将作为实体出现。
    • 您可以使用@JsonValue 注释自定义对象的序列化方式。在此处查看所有支持的注释wiki.fasterxml.com/JacksonAnnotations
    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    相关资源
    最近更新 更多