【问题标题】:what is the equivalent of ruby YAML.load(object) and YAML.dump(serialized_str) in javajava中ruby YAML.load(object)和YAML.dump(serialized_str)的等价物是什么
【发布时间】:2025-12-29 23:15:18
【问题描述】:

在 ruby​​ 中,我可以像这样序列化和反序列化:

# file.rb
class C

end

s = YAML.dump(C.new)
# other_file_and_other_time.rb
r = YAML.load(s)
puts "r.inspect:#{r.inspect} ---- #{::File.basename __FILE__}:#{__LINE__}"
# r.inspect:#<C:0x007f4ff27e6c08> ---- timer.rb:9

在java中,我可以做类似的事情:

package ro.ex;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

class Ex {
    static class MyArrayList<E> extends ArrayList<E> {
        public MyArrayList(Collection c) {
            super(c);
        }

    }

    public static void main(String[] args) throws IOException {
        // file.java
        String s = new Gson().toJson(new Ex());
        // otherFile.java
        Object r = new Gson().fromJson(s, Ex.class);
        System.out.println(r + "\t\t" + new Exception().getStackTrace()[0].getFileName() + ":" + new Exception().getStackTrace()[0].getLineNumber());
    }

}

但我希望省略类型参数:

package ro.ex;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

class Ex {
    static class MyArrayList<E> extends ArrayList<E> {
        public MyArrayList(Collection c) {
            super(c);
        }

    }

    public static void main(String[] args) throws IOException {
        // file.java
        String s = new Gson().toJson(new Ex());
        // otherFile.java
        Object r = new Gson().fromJson(s);
        System.out.println(r + "\t\t" + new Exception().getStackTrace()[0].getFileName() + ":" + new Exception().getStackTrace()[0].getLineNumber());
    }

}

所以我的问题是:如何在没有特定类型的情况下反序列化。(传递最后一个代码)

【问题讨论】:

    标签: java android ruby serialization deserialization


    【解决方案1】:

    Ruby 是一种“鸭子”、动态类型语言,正因为如此,你可以做这样的事情。 但是 Java 有一个静态的、安全的和强大的类型规则,所以你不能做这样的事情。

    但是,由于您已在“android”标签下标记了您的问题,Parcelable interface 可以帮助您,需要更多代码,但它正是您要找的。​​p>

    同时检查这些链接:

    【讨论】: