在Android中获得Json结果

时间:2011-07-07 11:42:43

标签: android json

Json问题:

我有这种格式化的JSON

 {
 "Table1":[
  {
     "TableName":"LoadDistributor",
     "Description":"Distributor ",
     "MandatoryFlag":"1",
     "Status":"",
     "Priority":"0"
  },
  {
     "TableName":"LoadPrice",
     "Description":"Price ",
     "MandatoryFlag":"1",
     "Status":"",
     "Priority":"0"
  },
  {
     "TableName":"LoadProduct",
     "Description":"Product ",
     "MandatoryFlag":"1",
     "Status":"",
     "Priority":"0"
  },
  {
     "TableName":"RD.AlternativeProductDetail",
     "Description":"AltProdutDetail",
     "MandatoryFlag":"0",
     "Status":"",
     "Priority":"0"
  },
  {
     "TableName":"XA.vwTown",
     "Description":"Town ",
     "MandatoryFlag":"1",
     "Status":"",
     "Priority":"0"
  }

] }

Android Json处理方法是:

   public String[] getStringArrayResponseJson(SoapPrimitive node, ArrayList<String> strings) {
    try{

        String result = node.toString();
        JSONObject json = new JSONObject(result);

        // Parsing
        JSONArray nameArray = json.names();
        JSONArray valArray = json.toJSONArray(nameArray);
        Log.i("@@@" , "===="+  valArray.length());
        for (int i = 0; i < valArray.length(); i++) {
            strings.add(valArray.getString(i));
        }

        json.put("sample key", "sample value");
        Log.i("REST", "<jsonobject>\n" + json.toString()
                + "\n</jsonobject>");
    }catch (JSONException e) {
    e.printStackTrace();
}

我的要求是我想将TableName转换为字符串[]或列表......我们如何做到这一点?

请帮助我json处理方法中的错误:?

1 个答案:

答案 0 :(得分:1)

示例代码,不确定它是否会起作用。 我只是为了它而为字符串创建一个ArrayList。

ArrayList<String> list = new ArrayList<String>();
JSONArray array = jsonobject.getJSONArray("Table1");        
int max = array.length();
 for (int i = 0; i < max; i++) {
   JSONObject tmp = array.getJSONObject(i);
   list.add(tmp.getString("TableName"));
 }

可能是一个更快捷的方式,但仅仅是一个例子。

您可以阅读更多http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/