如何解析JSONArray Android

时间:2017-04-25 21:18:35

标签: android arrays json

如果来自webservice的响应的格式如下,我如何解析JSONArray:

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://www.somewebsite.com/"><PricingTier ANo='01234567' MsgFlg=''><Group Type='Mouldings'><CurTier>BRZ</CurTier><NxtTier>SIL</NxtTier><CurTierFrom>$4,000</CurTierFrom><CurTierTo>$9,999</CurTierTo><NxtTierFrom>$10,000</NxtTierFrom><NxtTierTo>$14,999</NxtTierTo><CurSales>$2,107</CurSales><ReqSales>$7,893</ReqSales><MsgFull></MsgFull><MsgPart></MsgPart></Group><Group Type='Accessories'><CurTier>BAS</CurTier><NxtTier>GLD</NxtTier><CurTierFrom>$0</CurTierFrom><CurTierTo>$1,499</CurTierTo><NxtTierFrom>$1,500</NxtTierFrom><NxtTierTo>$4,999</NxtTierTo><CurSales>$125</CurSales><ReqSales>$800</ReqSales><MsgFull></MsgFull><MsgPart></MsgPart></Group></PricingTier></string>

当我运行我的应用程序时,我收到一条错误消息“无法将字符串转换为JSONObject”。我知道它不喜欢如何格式化字符串响应,所以我想知道我可以做什么修改来将响应(JSON_DATA)格式化为解析器可以正确使用的东西。

代码:

 if (JSON_DATA != null) {

            try {
                JSONObject reader = new JSONObject(JSON_DATA);

                JSONArray Group = reader.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");

                    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);
                        }
                    });
                }

1 个答案:

答案 0 :(得分:0)

网址目标是网络服务,而不是网络代理。因此,结果是XML而不是JSON。