【问题标题】:How to get the value with GSON / Retrofit? [duplicate]如何通过 GSON / Retrofit 获得价值? [复制]
【发布时间】:2019-03-05 16:55:05
【问题描述】:

如何使用 GSON/Retrofit 提取“文本”的值?

    {
       code: 200,
       lang: "en-ms",
       text: [
           "Burung"
       ]
    }

【问题讨论】:

  • 你能成功调用API吗?
  • 是的,API调用成功
  • 请尝试谷歌“如何使用 POJO 进行改造”

标签: android json gson retrofit2


【解决方案1】:

像地图这样的文本。您需要使用

创建 pojo
@SerializedName("code")
    @Expose
    private int mCode;

@SerializedName("lang")
    @Expose
    private String mLang;

@SerializedName("text")
    @Expose
    private Map <String, List<String> mText;

使用工厂 (GsonFactory) 创建改造。并实例化这个 pojo。

p.s: 你也可以为你的对象制作序列化器和反序列化器

【讨论】:

    【解决方案2】:

    制作给定响应的 POJO 类,并将其注册到改造回调中,并在 getter 和 setter 的帮助下获取值。

    【讨论】:

      【解决方案3】:

      1 创建您的模型类

      public class ResponseItem {
      
      /**
       * code : 200
       * lang : en-ms
       * text : ["Burung"]
       */
      
      private int code;
      private String lang;
      private List<String> text;
      
      public int getCode() {
          return code;
      }
      
      public void setCode(int code) {
          this.code = code;
      }
      
      public String getLang() {
          return lang;
      }
      
      public void setLang(String lang) {
          this.lang = lang;
      }
      
      public List<String> getText() {
          return text;
      }
      
      public void setText(List<String> text) {
          this.text = text;
      }
      

      }

      2 在您的 Retrofit 方法响应中:

       if (response.isSuccessful()) {
        ResponseItem responseItem;
        responseItem = response.body(); }
      

      你可以通过 responseitem.Get("whatever u want from the model class") 来调用文本

      【讨论】:

      • 它对我有用,谢谢,我怎样才能删除“[]”
      【解决方案4】:

      您可以使用以下代码获取 json 中的所有对象并放入数组中:

      JSONArray texts = new JSONObject(json).getJSONArray("text");
      

      【讨论】:

      • 这不是GSON
      猜你喜欢
      • 2015-09-19
      • 1970-01-01
      • 2021-03-20
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2012-10-09
      相关资源
      最近更新 更多