【问题标题】:deserialize using Gson gives "Failed to invoke public okhttp3.RequestBody() with no args"使用 Gson 反序列化给出“无法调用没有参数的公共 okhttp3.RequestBody()”
【发布时间】:2019-07-28 09:50:53
【问题描述】:

我正在尝试在没有互联网连接时缓存一些网络调用,以便稍后重试,

我通过使用Gson.toJson(...) 序列化 okhttp3.Request 对象来做到这一点 (以及其他一些信息,如时间戳等)。并且序列化工作正常,并且检查了生成的 JSON,并且所有数据都按预期存在。

但是,当我后来想用 Gson.FromJson(...) 反序列化 json 时,它会抛出一个错误:

java.lang.RuntimeException: 调用公共失败 okhttp3.RequestBody() 没有参数


我一直无法弄清楚如何解决此错误。

任何帮助将不胜感激。

[编辑] 我按如下方式构建主体:

FormBody.Builder body = new FormBody.Builder();
body.add({name}, {value});
body.add({name}, {value});
body.build();

【问题讨论】:

  • 您能否展示一下您是如何构建RequestBodyRequest 对象的? RequestBody 是一个 abstract class 并且没有办法在没有参数的情况下调用 constructor。可能您需要为给定类型实现自定义序列化器和反序列化器。

标签: java android gson deserialization okhttp3


【解决方案1】:

所以我认为反序列化 okhttp3.Request 对象是行不通的。

相反,我创建了一个简单的结构“PostBodyHolder”,将其构建为请求对象,然后将其缓存,当我实际执行请求时,我从 PostBodyHolder 构建 okhttp3.Request 对象。

public class PostBodyHolder {

    /**
     * The params of this body.
     */
    public final List<Param> params = new ArrayList<>();
    /**
     * The URL for this body.
     */
    public String url;

    public PostBodyHolder(String url) {
        this.url = url;
    }

    public PostBodyHolder add(@NonNull String name, @NonNull String value) {
        params.add(new Param(name, value));
        return this;
    }

    /**
     * Holder for body params.
     */
    public class Param {

        /**
         * The name of the Param
         */
        public String name;
        /**
         * The Value of the Param
         */
        public String value;

        public Param(@NonNull String name, @NonNull String value) {
            this.name = name;
            this.value = value;
        }
    }
}

对这里感兴趣的人可以使用 Kotlin 版本

class PostBodyHolder(
        /**
         * The URL for this body.
         */
        var url: String) {

    /**
     * The params of this body.
     */
    val params: MutableList<Param> = ArrayList()

    fun add(name: String, value: String): PostBodyHolder {
        params.add(Param(name, value))
        return this
    }

    /**
     * Holder for body params.
     */
    inner class Param(
            /**
             * The name of the Param
             */
            var name: String,
            /**
             * The Value of the Param
             */
            var value: String)
}

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多