首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否从序列化中排除类和命名空间?

是否从序列化中排除类和命名空间?
EN

Stack Overflow用户
提问于 2013-12-16 03:13:53
回答 2查看 172关注 0票数 0

我正在尝试用Jackson序列化一个相当大的结构。

然而,它也试图导出很多我永远不需要的子结构(导致JsonMappingException: No serializer found for class)

那么,如何从序列化中排除类和命名空间呢?

或者,如何将类的属性标记为已排除/忽略?

EN

回答 2

Stack Overflow用户

发布于 2013-12-16 03:18:10

如果对要排除的子结构具有实际访问权限,请使用瞬态关键字。

Java瞬态是一个

关键字,当成员变量被持久化到字节流时,它会标记为不被序列化。当一个对象通过网络传输时,该对象需要被“序列化”。序列化将对象状态转换为串行字节。这些字节通过网络发送,并从这些字节重新创建对象。由java瞬态关键字标记的成员变量不会被传输,它们是故意丢失的。

http://en.wikibooks.org/wiki/Java_Programming/Keywords/transient

票数 1
EN

Stack Overflow用户

发布于 2013-12-16 03:24:20

请为排除类和命名空间提供一个示例,但对于您可能无法控制其源代码的属性,您可以在类型和字段上使用以下内容

代码语言:javascript
复制
@JsonIgnoreProperties(value = {"propertyName", "otherProperty"})

Here's the javadoc.

下面是一个例子

代码语言:javascript
复制
@JsonIgnoreProperties(value = { "name" })
public class Examples {
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        Examples examples = new Examples();
        examples.setName("sotirios");
        Custom custom = new Custom();
        custom.setValue("random");
        custom.setNumber(42);
        examples.setCustom(custom);
        ObjectMapper mapper = new ObjectMapper();
        StringWriter writer = new StringWriter();

        mapper.writeValue(writer, examples);
        System.out.println(writer.toString());
    }

    private String name;

    @JsonIgnoreProperties(value = { "value" })
    private Custom custom;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Custom getCustom() {
        return custom;
    }

    public void setCustom(Custom custom) {
        this.custom = custom;
    }

    static class Custom {
        private String value;
        private int number;
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
        public int getNumber() {
            return number;
        }
        public void setNumber(int number) {
            this.number = number;
        }
    }
}

打印

代码语言:javascript
复制
{"custom":{"number":42}}

换句话说,它忽略了Examples#nameCustom#value

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20598607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档