java - 使用 protostuff 反序列化数组

标签 java json serialization deserialization protostuff

我正在尝试使用protostuff来序列化反序列化json,但是当我序列化对象时,数组的大小放在前面

{"id":1,"price":1.2,"name":"alex","tags":{"a":3,"b":["tag1","tag2","tag2"]}}

如果我尝试对同一个字符串进行反序列化,它的工作方式就像一个魅力,但我的数据没有“a”:3,“b”:对于标签来说它很简单

{"id":1,"price":1.2,"name":"alex","tags":["tag1","tag2","tag2"]}

当我尝试对上面这样的字符串进行反序列化时,我会抛出异常

 io.protostuff.JsonInputException: Expected token: { but was VALUE_STRING on tags of message java.lang.reflect.Array

使用的java代码:

String[] x = {"tag1", "tag2", "tag2"};
Product t = new Product(1, 1.2, "alex", x);
Path path = Paths.get("...");
byte[] as = Files.readAllBytes(path);
io.protostuff.Schema<Product> schema = RuntimeSchema.getSchema(Product.class);
LinkedBuffer buffer = LinkedBuffer.allocate(512);

byte[] protostuff;
try {
    protostuff = JsonIOUtil.toByteArray(t, schema, false , buffer);
} finally {
    buffer.clear();
}
// deser
Product f = schema.newMessage();
JsonIOUtil.mergeFrom(as, f, schema,false);

产品类别:

public class Product {
    private int id;
    private double price;
    private String name;
    private String[] tags;

    public Product(int id, double price, String name, String[] tags) {
        this.id = id;
        this.price = price;
        this.name = name;
        this.tags = tags;
    }

    public Product() {
    }



    public int getId() {
        return id;
    }

    public double getPrice() {
        return price;
    }

    public String getName() {
        return name;
    }

    public String[] getTags() {
        return tags;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setPrice(double price) {
        this.price = price;
    }

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

    public void setTags(String[] tags) {
        this.tags = tags;
    }

    @Override
    public String toString() {
        return name+" "+ price+" "+ id+" "+ Arrays.toString(tags);
    }    
}

最佳答案

Protostuff 使用 special schema用于序列化数组 - 出于性能原因,它将数组大小转换为序列化形式。

您应该将tags的字段类型更改为List:

private List<String> tags;

列表直接序列化为 JSON 数组:

{"id":1,"price":1.2,"name":"alex","tags":["tag1","tag2","tag2"]}

关于java - 使用 protostuff 反序列化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30678186/

相关文章:

java - 安卓, "Error in an XML file: aborting build."

json - 为什么 golang 自定义解码得到零结构

C++ - boost::any 序列化

java - 如何在不调整图像大小的情况下压缩PDF?

java - 如何在 JButton 上运行线程?

python - Python中输出json txt名称

javascript - 使用 ODATA 格式的 javascript 发布数据

c# - 序列化对于对象大小估计可靠吗?

java - ActionListener 和 IF 语句出现问题

json - HIVE,如何从数组中获取元素,元素本身也是一个数组