简体   繁体   English

如何在Java中将通用对象序列化为Json以及反序列化Json为对象

[英]how to serialize a general object to Json and deserialize Json to the object in Java

Is there a way to serialize a general object to Json and deserialize Json to the object? 有没有一种方法可以将通用对象序列化为Json并反序列化Json到该对象?
If the object is an entity, I can use Jackson 2 lib to achieve the purpose. 如果对象是实体,则可以使用Jackson 2 lib达到目的。
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. 例如,我想将com.datastax.driver.core.querybuilder.Update序列com.datastax.driver.core.querybuilder.Update Json并将其保存到DB,然后搜索并反序列化为Update对象,最后将其用作com.datastax.driver.core.Session.execute(Statement)的参数com.datastax.driver.core.Session.execute(Statement)

Is it possible to reproduce Update object? 是否可以复制Update对象?

COMPLEMENT : 补品

My real purpose is to store Update and then retrieve and execute it. 我的真正目的是存储Update ,然后检索并执行它。 So I thought I could save it as JSON String and then retrieve and deserialize it into the original Update instance and execute it. 所以我想我可以将其另存为JSON String ,然后将其检索并反序列化为原始Update实例并执行它。 If It's not a good way, how can I store Update and then retrieve and execute it? 如果这不是一个好方法,如何存储Update ,然后检索并执行它?
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 . 尽管我可以存储Updatetext query以及检索和执行text query ,但是Update其他一些信息可能会丢失,例如ConsistencyLevel

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. 因为例如对该Update类的更改可能会轻易破坏您的自定义(反)序列化器代码。

org.json offers a simple API that manipulates json. org.json提供了一个操作json的简单API。 There is a method that creates a JSONObject of an instance of a class based on its getter. 有一种方法可以根据其getter创建类的实例的JSONObject。 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 : 该API还提供了差异解析器,您可以使用提供的JSONObject对类的构造函数进行编码:

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

Full doc at : org.json official doc 完整文档位于: org.json官方文档

Just Convert the QueryBuilder.update into string using toString() method 只需使用toString()方法将QueryBuilder.update转换为字符串

If you want to store,retrieve and execute the QueryBuilder.update query, you don't have to serialized and deserialized it into json. 如果要存储,检索和执行QueryBuilder.update查询,则无需将其序列化和反序列化为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() 这是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 您可以看到它正在返回实际的查询字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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