gpt4 book ai didi

Android - 如何从字符串中解析 JsonArray?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:25:16 25 4
gpt4 key购买 nike

我试图从 json 字符串解析一个 json 数组,但它总是抛出异常 data of type java.lang.String cannot be converted to JSONArray

如果我有任何错误,请告诉我。

谢谢。

这是我从服务器获取 Json 的代码:

try {
String url = String.format(<url here>, province.provinceCode2);
HttpClient httpClient = getHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
final String result = EntityUtils.toString(entity);
parseAndSaveJsonData(province, result);
} catch (Exception e) {
e.printStackTrace();
}

这里是解析 JsonArray 的代码:

String jsonString = <below json string>
JSONArray ja = new JSONArray(jsonString);

这是我的 json 字符串:

   [
{
"LotPrizes":[
{
"Prize":"Giảitám",
"Range":"50"
},
{
"Prize":"Giảibảy",
"Range":"264"
},
{
"Prize":"Giảisáu",
"Range":"3654-5162-3097"
},
{
"Prize":"Giảinăm",
"Range":"9739"
},
{
"Prize":"Giảitư",
"Range":"97690-99274-32442-69432-04855-10132-17085"
},
{
"Prize":"Giảiba",
"Range":"73745-13007"
},
{
"Prize":"Giảinhì",
"Range":"05521"
},
{
"Prize":"Giảinhất",
"Range":"74870"
},
{
"Prize":"GiảiDB6",
"Range":"878833"
}
]
},
{
"LotPrizes":[
{
"Prize":"Giảitám",
"Range":"50"
},
{
"Prize":"Giảibảy",
"Range":"264"
},
{
"Prize":"Giảisáu",
"Range":"3654-5162-3097"
},
{
"Prize":"Giảinăm",
"Range":"9739"
},
{
"Prize":"Giảitư",
"Range":"97690-99274-32442-69432-04855-10132-17085"
},
{
"Prize":"Giảiba",
"Range":"73745-13007"
},
{
"Prize":"Giảinhì",
"Range":"05521"
},
{
"Prize":"Giảinhất",
"Range":"74870"
},
{
"Prize":"GiảiDB6",
"Range":"878833"
}
]
}

]

最佳答案

这是初始化 JSON 解析器的方法:

JSONObject jsonObject = new JSONObject(jsonString);

这将为您提供整个字符串作为 Json 对象。从那里,拉出一个单独的数组作为 JsonArray,如下所示:

JSONArray jsonArray = jsonObject.getJSONArray("LotPrizes");

要访问每个“LotPrizes”,您可以使用循环逻辑:

for(int i=0;i<jsonArray.length();i++)
{
JSONObject curr = jsonArray.getJSONObject(i);

prize = curr.getString("Prize")

//Do stuff with the Prize String here
//Add it to a list, print it out, etc.
}

编辑:JSON 编辑后的最终代码:

JSONArray jsonArray = null;
String jsonString = <your string>
String currPrize = null;

JSONObject jsonObject = new JSONObject(jsonString);

jsonArray = jsonObject.getJSONArray("data");

for(int i=0;i<jsonArray.length();i++)
{
JSONArray currLot = jsonArray.getJSONObject(i);

for(int j=0; j<currLot.length();j++)
{
JSONobject curr = currLot.getJSONObject(j);

currPrize = curr.getString("Prize");

//Do something with Prize
}
}

这段代码是有效的,我在我的代码中使用了几乎相同的版本。希望这(最终)对您有用。

关于Android - 如何从字符串中解析 JsonArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14566533/

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