我有一個JSONArray,我可以解析,但由於數組的結構,我無法映射從具有相同名稱的字段中提取的值。而不是for循環分配一個接一個的值,分配查看字段名稱的最後一個實例。所以來自第二個JSONObject的值被分配兩次。在Android中使用相同字段名稱的JSONArray解析和值映射
"Group": [
{
"-Type": "Mouldings",
"CurTier": "BRZ",
"NxtTier": "SIL",
"CurTierFrom": "$4,000",
"CurTierTo": "$9,999",
"NxtTierFrom": "$10,000",
"NxtTierTo": "$14,999",
"CurSales": "$2,107",
"ReqSales": "$7,893"
},
{
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
}
]
代碼:
try {
JSONObject reader = new JSONObject(JSON_DATA);
JSONObject PricingTier = reader.getJSONObject("PricingTier");
JSONArray Group = PricingTier.getJSONArray("Group");
for (int i = 0; i < Group.length(); i++) {
JSONObject g = Group.getJSONObject(i);
final String Type = g.getString("@Type");
final String CurTier = g.getString("CurTier");
final String NxtTier = g.getString("NxtTier");
final String CurTierFrom = g.getString("CurTierFrom");
final String CurTierTo = g.getString("CurTierTo");
final String NxtTierFrom = g.getString("NxtTierFrom");
final String NxtTierTo = g.getString("NxtTierTo");
final String CurSales = g.getString("CurSales");
final String ReqSales = g.getString("ReqSales");
final String TypeA = g.getString("@Type");
final String CurTierA = g.getString("CurTier");
final String NxtTierA = g.getString("NxtTier");
final String CurTierFromA = g.getString("CurTierFrom");
final String CurTierToA = g.getString("CurTierTo");
final String NxtTierFromA = g.getString("NxtTierFrom");
final String NxtTierToA = g.getString("NxtTierTo");
final String CurSalesA = g.getString("CurSales");
final String ReqSalesA = g.getString("ReqSales");
fragment.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
tvType.setText(Type);
tvCurTier.setText(CurTier);
tvNxtTier.setText(NxtTier);
tvCurTierFrom.setText(CurTierFrom);
tvCurTierTo.setText(CurTierTo);
tvNxtTierFrom.setText(NxtTierFrom);
tvNxtTierTo.setText(NxtTierTo);
tvCurSales.setText(CurSales);
tvReqSales.setText(ReqSales);
tvTypeA.setText(TypeA);
tvCurTierA.setText(CurTierA);
tvNxtTierA.setText(NxtTierA);
tvCurTierFromA.setText(CurTierFromA);
tvCurTierToA.setText(CurTierToA);
tvNxtTierFromA.setText(NxtTierFromA);
tvNxtTierToA.setText(NxtTierToA);
tvCurSalesA.setText(CurSalesA);
tvReqSalesA.setText(ReqSalesA);
}
});
}
結果:
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
當我嘗試這一點,我fragment.getActivity線程不能訪問收到的字符串。有沒有辦法來解決這個問題? –
啊謝謝你!我簡單地把runOnUiThread放在(if == 0)和(if == 1)裏面,它工作正常。 –