0

Is there a way to serialize a general object to Json and deserialize Json to the object?
If the object is an entity, I can use Jackson 2 lib to achieve the purpose.
But if the object is a general class, how can I do this?

For example, I'd like to serialize com.datastax.driver.core.querybuilder.Update to Json and save it to DB, then search and deserialize it to Update object, finally use it as the argument of com.datastax.driver.core.Session.execute(Statement) to execuate.

Is it possible to reproduce Update object?

COMPLEMENT:

My real purpose is to store Update and then retrieve and execute it. So I thought I could save it as JSON String and then retrieve and deserialize it into the original Update instance and execute it. If It's not a good way, how can I store Update and then retrieve and execute it?
Though I can store the text query of Update and the retrieve and execute the text query, some other information in Update maybe lose, like ConsistencyLevel.

niaomingjian
  • 3,472
  • 8
  • 43
  • 78

3 Answers3

0

Worst case, you can always look into creating your own custom (de)serializer code.

See here or there for further reading.

Meaning: you can look into the implementation of the class you intend to "serialize"; and then write code that works for that implementation.

The major downside when doing that for 3rd party code is: you now have to keep track of changes to that 3rd party code; as changes to that Update class for example might easily break your custom (de)serializer code.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • My real purpose is to store `Update` and then retrieve and execute it. So I wonder if I can use Json format to store it. Are there other ways to do that? – niaomingjian Jun 20 '17 at 01:16
  • I gave you input that describes how to store objects of arbitrary classes. I really don't get your point. There is no magic here. *You* have to look into the implementation of the class you intend to serialize and then write code. The only alternative I can think if: Google gson works using reflection, so it does not need the getter/setter methods that Jackson expects. But then it sounds like you are overburdened anyway. Finally: you find all the answers worth "repeating" your question, but none of them is good enough for an upvote? Very motivating... – GhostCat Jun 20 '17 at 02:16
0

org.json offers a simple API that manipulates json. There is a method that creates a JSONObject of an instance of a class based on its getter. For example:

public class MyClass{
    private int id;
    private String name,

    public MyClass(int id_, String name_) {
        this.id = id_;
        this.name = name_;
    }

    public int getId() { return this.id; }
    public int getName() { return this.name; }

    //Create a JSONObject with a key-value for each getter of your class
    public JSONObject toJson(){
        return new JSONObject(this);
    }
}

Then, in your code :

MyClass obj = new MyClass(1, "doe");
JSONObject json = obj.toJson();
System.out.println(json.toString());
// -> print : {"id":1,"name":"doe"}

The API also provides differents parser, and you can code a constructor of your class with a JSONObject provided :

public MyClass(JSONObject json){
     this.id= json.getInt("id");
     this.name= json.getString("name");
}

Full doc at : org.json official doc

Asew
  • 374
  • 2
  • 13
0

Just Convert the QueryBuilder.update into string using toString() method

If you want to store,retrieve and execute the QueryBuilder.update query, you don't have to serialized and deserialized it into json.

String query = QueryBuilder.update("exp").with(QueryBuilder.set("data", "This is a test data")).toString();
//Now you can store the text query directly to cassandra
//And retrieve the text query
session.execute(query); //Execute the query

Here is the code of toString()

@Override
public String toString() {
    try {
        if (forceNoValues)
            return getQueryString();
        // 1) try first with all values inlined (will not work if some values require custom codecs,
        // or if the required codecs are registered in a different CodecRegistry instance than the default one)
        return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString();
    } catch (RuntimeException e1) {
        // 2) try next with bind markers for all values to avoid usage of custom codecs
        try {
            return maybeAddSemicolon(buildQueryString(new ArrayList<Object>(), CodecRegistry.DEFAULT_INSTANCE)).toString();
        } catch (RuntimeException e2) {
            // Ugly but we have absolutely no context to get the registry from
            return String.format("built query (could not generate with default codec registry: %s)", e2.getMessage());
        }
    }
}

You can see that It's returning the actual query string

Ashraful Islam
  • 12,470
  • 3
  • 32
  • 53
  • Yes, I want to store, retrieve and execute the `com.datastax.driver.core.querybuilder.Update` query. You mean using `toString()` method can get the correct text query and then execute it directly? Are you sure this is correct regarding **complex** update operation? I don't know what `toString()` method exactly do. The source code is a little diffcult for me. – niaomingjian Jun 20 '17 at 01:29
  • Though I can get the text query, I maybe lose some other information in `Update`. – niaomingjian Jun 20 '17 at 02:00
  • @niaomingjian Updated the answer added `toString()` code. You can see that It's returning the actual query string. – Ashraful Islam Jun 20 '17 at 04:16
  • Will it lose other information, like `ConsistencyLevel`, that was set in `Update`? I'm afraid of that. – niaomingjian Jun 20 '17 at 08:37
  • It only contains the query. consistency,defaultTimestamp etc will be lost – Ashraful Islam Jun 20 '17 at 08:46
  • I think so, too. Thank you very much. – niaomingjian Jun 20 '17 at 08:47