Deserializing arrays with protostuff

1.4k Views Asked by At

I am trying to use protostuff to serialize deserialize json but when i serialize the object the size of the array is put in front

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

if i trie to desirialize the same string it works like a charm but my data dosent have "a":3,"b": for the tags its just simple

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

when i trie to desirialize a string like the above i get an exception thrown

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

java code used:

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);

product class:

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);
    }    
}
1

There are 1 best solutions below

0
On BEST ANSWER

Protostuff uses special schema for serializing arrays - it puts array size to a serialized form for performance reasons.

You should change field type of tags to List:

private List<String> tags;

Lists are serialized directly into a JSON array:

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