gpt4 book ai didi

java - JSONObject内部多个JSONObject的Android JSON解析

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:48:22 26 4
gpt4 key购买 nike

我有一个来自服务器的 JSON 字符串,它看起来像这样:

{
"categories": {
"0": {
"term_id": "247",
"name": "Content Curation"
},
"1": {
"term_id": "50",
"name": "Content Marketing"
},
"2": {
"term_id": "2",
"name": "Curation"
},
"3": {
"term_id": "246",
"name": "Inbound Marketing"
},
"4": {
"term_id": "47",
"name": "Marketing"
},
"5": {
"term_id": "4",
"name": "News Curation"
},
"6": {
"term_id": "36",
"name": "SEO"
},
"8": {
"term_id": "248",
"name": "Wordpress Content Curation"
}
}
}

我的任务是获取“term_id”和“name”字段的值。我曾经使用以下代码从当前 JSONObject 获取“类别”对象:

JSONObject jObject = new JSONObject(responceData);
JSONObject categoryObject = jObject.getJSONObject("categories");
JSONArray jarray = new JSONArray("["+categoryObject.toString().substring(1,categoryObject.toString().length() - 1) + "]");

for(int i=0;i<jarray.length();i++)
{
JSONObject jobj = jarray.getJSONObject(i);
String term_id=jobj.getString("term_id");
String name=jobj.getString("name");
}

categoryObject 看起来像这样:

{
"0": {
"term_id": "247",
"name": "Content Curation"
},
"1": {
"term_id": "50",
"name": "Content Marketing"
},
"2": {
"term_id": "2",
"name": "Curation"
},
"3": {
"term_id": "246",
"name": "Inbound Marketing"
},
"4": {
"term_id": "47",
"name": "Marketing"
},
"5": {
"term_id": "4",
"name": "News Curation"
},
"6": {
"term_id": "36",
"name": "SEO"
},
"8": {
"term_id": "248",
"name": "Wordpress Content Curation"
}
}

但在那之后我不知道如何获取字段。有没有办法从 JSONObject 中获取所有 JSONObject 子对象?

如果你有源代码或者可以给我一个例子,请与我分享。

最佳答案

在这里你可以检索你所有的 json 数据,请求一个特定的键和 innerKey 来得到你想要的,干杯

    try
{
String jsonString="";//your json string here
JSONObject jObject= new JSONObject(jsonString).getJSONObject("categories");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
Log.v("**********", "**********");
Log.v("category key", key);
JSONObject innerJObject = jObject.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
String value = innerJObject.getString(innerKkey);
Log.v("key = "+key, "value = "+value);
}
}
}
catch (JSONException e)
{ e.printStackTrace(); }

关于java - JSONObject内部多个JSONObject的Android JSON解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606572/

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