简体   繁体   中英

safe json to java serialization/deserialization

I would like to know how you would do this :

I have a java data object. This object contains object attributes that contains object attributes...

I serialize my objects using json-io . But when deserializing, I want to protect the data if an object fails to deserialize. So I got the idea to json-serialize each attribute before serializing any object. This way, if an attribute fails to deserialize, the object itself is safe.

this means that if I have an object {a:v1,b:{ba:v2,bb:{bba:v3,bbb:v4}}} , I will serialize it like this instead : "{\\"a\\":\\"v1\\",\\"b\\":\\"{\\\\\\"ba\\\\\\":\\\\\\"v2\\\\\\",\\\\\\"bb\\\\\\":\\\\\\"{\\\\\\\\\\\\\\"bba\\\\\\\\\\\\\\":\\\\\\\\\\\\\\"v3\\\\\\\\\\\\\\",\\\\\\\\\\\\\\"bbb\\\\\\\\\\\\\\":\\\\\\\\\\\\\\"v4\\\\\\\\\\\\\\"}\\\\\\"}\\"}"

You see that on a very simple object it becomes very uneasy to read. Imagine with a more complex one !

I would like to do something about it, but I found no good ideas. Maybe the best would be when I read/write the json to call a function able to remove/re-add the "\\" where they are needed, but I don't succeed to find the correct algorithm... Any hint ? Or maybe another method ?

Thanks a lot !

Ok. My approach was wrong. I created a Data object like a Map that contains Data or String. Then, I can safely deserialize Data elements. It means that this time I have a tree, where all the trunk is a safe Data object, and only the leafs are json-serialized generic objects.

public class Data implements Serializable {
    private final Map<String, Data> node = new HashMap<>();//safe tree object

    private final Map<String, String> leafs = new HashMap<>();//unsafe serialized object
}

In my previous example, the result would be :

//initial object
{a:v1,b:{ba:v2,bb:{bba:v3,bbb:v4}}}
//becomes
{"a":"{v1}","b":{"ba":"{v2}","bb":{"bba":"{v3}","bbb":"{v4}"}}}

And the \\ would appear only if one of the unsafe values contains a String.

Thanks a lot Ryan, Talking to you helped me a lot to better define the problems, which is always the first step to the solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM