1

我正在尝试使用 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);
    }    
}
4

1 回答 1

0

Protostuff 使用特殊模式来序列化数组 - 出于性能原因,它将数组大小设置为序列化形式。

您应该将字段类型更改tags为列表:

private List<String> tags;

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

{"id":1,"price":1.2,"name":"alex","tags":["tag1","tag2","tag2"]}
于 2015-06-06T05:43:05.637 回答