JavaFX: How to deserialize dynamically create Area Chart Series?

后端 未结 1 1572
故里飘歌
故里飘歌 2021-01-28 04:00

I am adding series dynamically using list in Area Chart. I want to unwrap the series. I need this because I want to save Area Chart series data in db.

When app execute i

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 04:52

    There are various ways to accomplish this. Some are faster than others. I will show you one simple way ti can be done, but please note there are several.

    If speed is not a concern than I like to serialize objects into base64 text. This makes it very easy to mover around and store in DB's as text. If I was working on a project that required moving a lot of data an speed mattered, then I might not go with this approach.

    1) Use Java serialization to serialize the object into a byte[].

    protected byte[] convertToBytes(Object object) throws IOException {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutput out = new ObjectOutputStream(bos)) {
            out.writeObject(object);
            return bos.toByteArray();
        }
    }
    
    protected Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInput in = new ObjectInputStream(bis)) {
            return in.readObject();
        }
    }
    

    These methods can be used to convert Java objects to convert objects into and out of byte[].

    2) Take the byte[] from step 1 and use it to serialize into base64 text. These two methods will turn your seriesContainer into base64 String, or will turn a base64 String into seriesContainer.

    public String toBase64() {
        try {
            return Base64.getEncoder().encodeToString(convertToBytes(seriesContainer));
        } catch (IOException ex) {
            throw new RuntimeException("Got exception while converting to bytes.", ex);
        }
    }
    
    public void initializeFromBase64(String b64) {
        byte[] bytes = Base64.getDecoder().decode(b64);
        try {
            this.seriesContainer = (LinkedList>) convertFromBytes(bytes);
        } catch (Exception ex) {
            throw new RuntimeException("Got exception while converting from bytes.", ex);
        }
    }
    

    3) Take the String from step 2 and put it into a DB, or read it from a DB.

    0 讨论(0)
提交回复
热议问题