android - 如何从 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 要复杂得多,但我在这里对其进行了简化,以便更好地理解和更快地提出建议。
解决方案
如何实现保留原件价值但复制和修改以供进一步使用的目标?
使用您的新值创建一个新LexicalEntry
对象,而不是像现在这样更改现有对象。
推荐阅读
- delphi-2009 - Microsoft.XMLDOM xml.load xml.parseError.errorCode 另一个用户的不同结果
- reactjs - 根据分配的角色创建、分配角色给用户和加载菜单
- python - 自动识别数据是否为表格文本格式
- kubernetes - Helm Chart 在容器死亡时定义容器上的 postStart 钩子的行为
- python - 与此应用交互需要 CDK CLI >= 1.16.0
- ios - 如何等待 MPMediaLibrary requestAuthorization 响应
- sql - 对所有具有 null 的列进行取消透视
- java - 从字符串中提取数字 kotlin
- scala - scala 猫 IOApp 应该如何获取 ExecutionContext?
- python - 将“√9-1”转换为“sqrt(9)-1”