Gson 没有得到完整的字符串值
Posted
技术标签:
【中文标题】Gson 没有得到完整的字符串值【英文标题】:Gson doesn't get the full string value 【发布时间】:2018-03-14 15:48:56 【问题描述】:我想从这个 json 响应中获取键 "FullName"
的值:
"Succeeded": true,
"DebugError": "",
"SystemUser":
"ID": 94,
"FullName": "John Smith",
"Email": "abcd@gmail.com",
"PhoneNumber": "0000000000",
"Country": "USA"
在onResponse
方法中我做了这个:
// code..
@Override
public void onResponse(JSONObject response)
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(response.getJSONObject("SystemUser").get("FullName").toString()));
reader.setLenient(true);
String name = gson.fromJson(reader, String.class);
Log.i( " name: ", name + "");
// I tried to use getString("FullName") but shows the same result.
// code..
Logcat 中的值为 => name: John
为什么不打印全名(约翰·史密斯)??
【问题讨论】:
在您的模型上使用 '/' 进行字符串读取,例如"SystemUser"+"FullName="+ FullName+ '\''+ "ID="+ ID+ ..... 【参考方案1】:您的 GSON 实施似乎是多余的。只需使用
response.getJSONObject("SystemUser").getString("FullName")
【讨论】:
我在代码中添加了一条注释,说明我试过了,但没有解决问题。 确认您的 JSON 响应记录response.toString()
。看起来反应不一样。【参考方案2】:
您可以选择更好的方法,而不是采用这种方式。大多数应用都有复杂的 json 结构,不建议采用这种方法。
通过将示例 json 复制粘贴到 jsonschema2pojo 来创建模型类。现在选择目标语言:Java
,注解风格:Gson
下载或复制粘贴生成的模型类并使用以下内容(假设您的类名称为UserDetails
)。
UserDetails userDetails = gson.fromJson(response.toString(), UserDetails.class);
现在您已经填充了所有值的模型类。检索你想要的。
注意: 变量名和内部类名应与 JSON 结构完全相同。更好地使用注释。否则模型类将无法正确填充
【讨论】:
我对所有其他请求都使用模型方法,但我认为在这种情况下我只需要一个值,因此不需要整个类模型。!?以上是关于Gson 没有得到完整的字符串值的主要内容,如果未能解决你的问题,请参考以下文章