首页 > 解决方案 > 如何从 Retrofit2.0 复制和修改 JSON 响应创建的 POJO 类对象

问题描述

例如,我收到以下 JSON 响应:

{
  "metadata": {
    "provider": "ABC"
  },
  "results": [
    {
      "id": "ace",
      "language": "en",
      "lexicalEntries": [
        {
          "lexicalCategory": "Noun"
        },
        { 
          "lexicalCategory": "Adjective"
        },
        {
          "lexicalCategory": "Verb"
        }
      ],
      "type": "headword",
      "word": "ace"
    }
  ]
}

我正在使用 Retrofit2.0 和 gson 来解析它并以下列方式映射到 POJO 类:

class QueryResponse {
    public Metadata metadata;
    public List<Result> results = null;
}
class Result {
    public String id;
    public String language;
    public List<LexicalEntry> lexicalEntries = null;
    public String type;
    public String word;
}

class LexicalEntry {
    public String lexicalCategory;
}

onResponse() 看起来像这样:

@Override
public void onResponse(Call<QueryResponse> call, Response<QueryResponse> response) {
     if (response.code() == 200) {
         Result result = response.body().results.get(0);
         lexicalEntries = result.lexicalEntries;
     }
}

现在我有另一种方法,我想创建自己的新 LexicalEntry 对象(即,reprecedLexicalEntry)并从从 JSON 检索到的值复制值,然后以我自己的方式修改它以进一步重用。

private void createSubWords(List<LexicalEntry> lexicalEntries) {
    LexicalEntry revisedLexicalEntry;
    for (int x = 0; x < lexicalEntries.size(); x++) {
        revisedLexicalEntry = lexicalEntries.get(x);
        revisedLexicalEntry.lexicalCategory = "Something...";
    }
}

发生的情况是,稍后,我尝试获取原始 JSON 的 lexicalCategory (lexicalEntries.get(x).lexicalCategory),它也更改为“Something...”,而不是其原始值。

如何实现保留原件价值但复制和修改以供进一步使用的目标?我只是希望我的问题足够清楚。

提前致谢!

PS,我正在使用的实际 JSON 要复杂得多,但我在这里对其进行了简化,以便更好地理解和更快地提出建议。

标签: androidjsongsonretrofit2pojo

解决方案


如何实现保留原件价值但复制和修改以供进一步使用的目标?

使用您的新值创建一个新LexicalEntry对象,而不是像现在这样更改现有对象。


推荐阅读