Android-带有类似于@SerializedName的内容,注释Retrofit2 Post / Patch请求主体



如果帖子/补丁主体看起来像这样

{
    "class_name" : {
        "field_a" : "fjdksljf"
        "field_b" : "jfsljd"
        ...
        etc.
    }
}

我有一个pojo

public class ClassName () {
    @SerializedName("field_a")
    String fieldA;
    @SerializedName("field_b")
    String fieldB;
    ... etc.
}

我想以

的方式传递
@PATCH("endpoint_url")
Call<ResponseBody> testFunction(@Body ClassName class)

如何使用JSON请求所需的class_name映射来注释课程本身,而无需创建一个请求class className并用序列化名称注释的请求类?

(我尝试用@SerializedName注释课程,但它给了我"不适用于键入"警告。)

这对我来说是一个很好的解决方案。虽然可以将其包装在另一堂课中,但在我的用例中确实没有任何意义,因为我的大多数帖子都需要我发送的pojo json密钥。

// to use the necessary @SerializedName annotations
String classNameJson = new Gson().toJson(className);    // {"field_a": "fjdksljf", "field_b" : "jfsljd", ... etc.}
JSONObject json = new JSONObject();
try {
     // must make this a new JSONObject or else it will handle classNameJson as a string and append unnecessary quotes
     json.put("class_name", new JSONObject(classNameJson));    
} catch (JSONException e) {
     // handle the error
}
String result = json.toString();

结果应打印出类似于此 {"class_name":{"field_a": "fjdksljf", "field_b" : "jfsljd", ... etc.}}

的东西

从以下文章中得出这个想法:

  • JSON带有GSON的单个键值
  • jsonobject.tostring:如何不逃脱斜线
  • Java附加对象json

最新更新