我的数组看起来像这样:
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
我的代码在android上处理数组,我的代码在函数上的问题" for"在我从文件中复制和编辑另一个代码之前:
JSONObject jsonObjsko = new JSONObject(rajaongkir);
String resultse = jsonObjsko.getString("results");
JSONArray jsonObjssto = new JSONArray(resultse);
JSONObject mJsonObject = jsonObjssto.getJSONObject(0);
costs = mJsonObject.getString("costs");
JSONArray jsonArray = new JSONArray(costs);
for (int k = 0; k < jsonArray.length(); k++) {
try {
JSONArray jsonArrayp = new JSONArray(costs);
JSONObject jsonObject = jsonArrayp.getJSONObject(k);
String serviceq = jsonObject.getString("cost");
String servicel = jsonObject.getString("service");
kon = String.valueOf(jsonArray.length());
kin = kin + k;
JSONArray jsonObjsstorng = new JSONArray(serviceq);
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
String values = mJsonObjectrng.getString("value");
ShipPerActiv wp = new ShipPerActiv(servicel, values);
arraylist.add(wp);
}
catch (JSONException e) {
e.printStackTrace();
}
}
ShipPerActiv for add arraylist的代码:
public class ShipPerActiv {
private String services;
private String hongkir;
public ShipPerActiv(String services,String hongkir) {
this.services = services;
this.hongkir = hongkir;
}
public String getservices() {return this.services; }
public String gethongkir() {return this.hongkir; }
}
我尝试使用kon
&amp;的harddebug kin
true
函数正常但不在我的listview上只有一个int(0)而不是int(1)~et
答案 0 :(得分:1)
首先将StringObject转换为JSONObject
并且不要忘记在字符串的第一个地方添加{
而在字符串的末尾添加}
:
JSONObject parentObject = new JSONObject("{"+"JsonString"+"}");
然后像这样解析你的对象:
try {
JSONObject parentObject = new JSONObject(a);
JSONArray results = parentObject.getJSONArray("results");
JSONObject resultsObject=results.getJSONObject(0);
JSONArray costsArray = resultsObject.getJSONArray("costs");
for (int i = 0; i < costsArray.length(); i++) {
Log.d("CostsJsonObject" , costsArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
Log.d("CostsJsonObject Exception" , e.toString());
}
结果:
答案 1 :(得分:0)
我认为你的问题出现在这段代码上:
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
只需将其更改为:
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(0);
希望它会帮助你;)