gpt4 book ai didi

java - 如何在android中获取jsonObject值的值?

转载 作者:行者123 更新时间:2023-11-30 11:05:23 29 4
gpt4 key购买 nike

我正在构建一个 android 应用程序,我是 json 的新手。我在 josn formate 下面获取 -

{
"contact"[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}

我正在使用下面的代码来获取 key1 值。现在我面临的问题是如何获取 key3 值 -

jsonString = http.makeServiceCall(url, ServiceHandler.GET, null);
if (jsonString != null) {
try {
JSONObject jsonObj = new JSONObject(jsonString);

// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

请帮帮我

最佳答案

如果你想使用Gson来解析你的json数据。让我们试试吧:

首先,您必须像这样修改您的 json:

{
"contact":[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}

其次 将 Gson 添加到您的库并同步 build.gradle:下载 here提取它,并将 gson-2.2.4.gson 复制/粘贴到 libs 文件夹。

第三 创建一些类:

完整内容.java:

public class FullContents {
private List<ObjectKey> contact;

public List<ObjectKey> getContact() {
return contact;
}

public void setContact(List<ObjectKey> contact) {
this.contact = contact;
}
}

对象键.java:

public class ObjectKey {
private String key1;

private List<ObjectKey3> key2;

public List<ObjectKey3> getKey2() {
return key2;
}

public void setKey2(List<ObjectKey3> key2) {
this.key2 = key2;
}

public String getKey1(){
return key1;
}
public void setKey1(String key1){
this.key1 = key1;
}
}

ObjectKey3.java:

public class ObjectKey3 {
private String key3;
public String getKey3(){
return key3;
}
public void setKey3(String key3){
this.key3 = key3;
}
}

最后,从url获取数据:

 private class ParseByGson extends AsyncTask<String,Void,FullContents> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected FullContents doInBackground(String... params) {
FullContents fullContents = null;
try {
URL url=new URL(params[0]);
InputStreamReader reader=new InputStreamReader(url.openStream(),"UTF-8");
fullContents=new Gson().fromJson(reader,FullContents.class);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fullContents;
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(FullContents results) {
super.onPostExecute(results);
ObjectKey objectKey = results.getContact().get(0);
Log.e(">>",objectKey.getKey1()+"--");
}
}

你可以把下面的代码放到onCreate:

ParseByGson parseByGson = new ParseByGson();
parseByGson.execute(urlStringHere);

更新:解释

enter image description here

关于java - 如何在android中获取jsonObject值的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659169/

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