2012-01-13 108 views
3

以下是我的JSON文件: -如何使用Json解析?

"Restaurants":{ 

    "8":{ 
     "Res_name":"Purple Cafe and Wine Bar", 
     "foodtype":"American, Wine", 
     "city":"Seattle", 
     "state":"WA", 
     "latitude":"0", 
     "longitude":"0" 
    }, 
    "9":{ 
     "Res_name":"Quinn's", 
     "foodtype":"American, Pubs", 
     "city":"Seattle", 
     "state":"WA", 
     "latitude":"0", 
     "longitude":"0" 
    }, 
    "19":{ 
     "Res_name":"Dahlia Lounge", 
     "foodtype":"American", 
     "city":"Seattle", 
     "state":"WA", 
     "latitude":"0", 
     "longitude":"0" 
    }, 
}, 

我使用下面的代碼爲JSON解析: -

try { 
    JSONObject jsonObj = new JSONObject(res); 
    JSONObject mRestaurant = jsonObj.getJSONObject("Restaurants"); 
    String mResult = jsonObj.getString("Result"); 
    System.out.println("mRestaurant is:- " + mRestaurant); 
} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

的mRestaurant值低於: -

{"487":{"state":"WA","Res_name":"SAM Taste","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"332":{"state":"WA","Res_name":"Luna Park Cafe","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"35":{"state":"WA","Res_name":"Restaurant Zoe","longitude":"0","latitude":"0","foodtype":"American, Bar","city":"Seattle"}," 

但什麼是獲得Res_Name的下一步,食物類型從上面的反應。

任何幫助,將不勝感激。

回答

3

下面的代碼是json解析的下一步。

public void getdata() { 
    String res = mWebRequest.performGet(Constants.url+ "restaurants.php? action=searchRestaurant&lat=0&lon=0&foodtype="+ mEdttxtSearch.getText().toString() + "&state="+ mEdttxtSearch.getText().toString() + "&city="+                    mEdttxtSearch.getText().toString()+ "&devType=Android"); 
    System.out.println("res is:- " + res); 
    if (res != null) { 
     try { 
      JSONObject jsonObj = new JSONObject(res); 
      JSONObject mRestaurants = jsonObj.getJSONObject("Restaurants"); 
      String mResult = jsonObj.getString("Result"); 
      if (jsonObj.has("Restaurants")) { 
       Iterator<Object> keys = mRestaurants.keys(); 
       while (keys.hasNext()) { 
        String key = (String) keys.next(); 
        JSONObject obj = new JSONObject(); 
        obj = mRestaurants.getJSONObject(key); 
        mRes_Name.add(obj.getString("Res_name")); 
        mLatitude.add(obj.getString("latitude")); 
        mLongitude.add(obj.getString("longitude")); 
        mState.add(obj.getString("state")); 
        mCity.add(obj.getString("city")); 
        mFood_Type.add(obj.getString("foodtype")); 
       } 
      } 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 
2

使用get()方法:

String mRestaurant = jsonObj.get("487").get("Res_name"); 
+1

這裏487是不固定的。 – 2012-01-13 12:15:05

+1

這是一個例子;想辦法。對不起,你忽略了告訴你需要喂什麼大小的勺子。 – duffymo 2012-01-13 12:45:27

+0

你好Duffymo上面的代碼給我錯誤。 – 2012-01-13 12:51:57