gpt4 book ai didi

java - 使用 protostuff 反序列化数组

转载 作者:太空宇宙 更新时间:2023-11-04 13:47:33 25 4
gpt4 key购买 nike

我正在尝试使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com