gpt4 book ai didi

android - 如何从 ANDROID 服务的 HTTP 响应中分别获取每个字符串?

转载 作者:太空狗 更新时间:2023-10-29 16:17:11 24 4
gpt4 key购买 nike

我在下面提到了响应代码。

switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
String responseBody = EntityUtils.toString(entity);
Log.d("Responce", responseBody.toString());
}
break;
}

此代码显示如下响应:

{"id":9,"name":"babu","role":5,"rights":"IsDelivery","result":"}

我想将每个值存储在单独的字符串中。像 Sting id = 3; Sting name = babu

请给我解决方案。

最佳答案

有两个选项:

更简单:创建一个将键作为属性的类,如下所示:

class MyEntity {
private int id;
private String name;
private int roles;
private String rights;
// ... other attributes;

// setters and getters and constructors?
}

然后使用 Gson 库(在此处 https://code.google.com/p/google-gson/Android Studio 的 maven 存储库中),并执行以下操作:

MyEntity myEntity = new Gson().fromJson(responseBody);

困难

使用JSONObject 手动获取每个值:

 JSONObject mainObject = new JSONObject(responseBody);
int id = mainObject.getInt("id");
String name = mainObject.getString("name");
// ....

关于android - 如何从 ANDROID 服务的 HTTP 响应中分别获取每个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24142624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com