2013-12-08 97 views
-1

我正在参加大学的组项目,我需要以指定的格式创建JSON POST请求。我遇到困难的部分是循环访问存储的对象数组,从对象获取值并使用所述值创建JSON对象。Android创建JSON POST,如何使用JSON对象/数组创建此格式

格式:

{ 
    "authorization": { 
     "hash": "427339AC646C25EFFA6B624CE776FB4FEE99CEDA", 
     "salt": "swordfish" 
    }, 
    "walk": { 
     "title": "Whitehall Wander", 
     "shortDesc": "A short walk around Westminster", 
     "longDesc": "A walk around London, viewing sights such as Downing Street, Trafalgar Square, and Scotland Yard", 
     "locations": [ 
      { 
       "latitude": 51.503396, 
       "longitude": 0.127640, 
       "timestamp": 0, 
       "descriptions": [ 
        "10 Downing Street" 
       ], 
       "images": [ 
        "no10door", 
        "primeminister" 
       ] 
      }, 
      { 
       "latitude": 51.506758, 
       "longitude": 0.128692, 
       "timestamp": 20, 
       "descriptions": [ 
        "Admiralty Arch" 
       ], 
       "images": [ 
       ] 
      }, 
      { 
       "latitude": 51.49861, 
       "longitude": 0.13305, 
       "timestamp": 60, 
       "descriptions": [ 
        "New Scotland Yard", 
        "Metropolitan Police HQ" 
       ], 
       "images": [ 
        "revolvingsign" 
       ] 
      } 
     ] 
    } 

我的问题是如何可以访问的变量在我的对象,所以我做这样的事情:

try{ 
     JSONObject auth = new JSONObject(); 
    JSONObject walk = new JSONObject(); 
    JSONObject location = new JSONObject(); 
    JSONArray points = new JSONArray(); 
    JSONObject image = new JSONObject(); 

    auth.put("AUTH TEST"); 

    for(int i = 0; i < pois.size(); i ++){ 


     points.put("name", pois.get(i).getName()); 

    } 


} catch (JSONException e) { 
    e.printStackTrace(); 
} 

这将引发一个错误:

The method put(int, boolean) in the type JSONArray is not applicable for the arguments (String, String) 

有没有办法做到这一点,因此它符合上述格式?

在POI的每个元素的变量是:

name = String 
description = String 
latitude = Double 
longitude = Double 

感谢。

回答

0

您得到它的错误导致JSONArray不能包含一组键/值。它可以包含JSONObjectStringint等情况......

Firstable,你应该张贴更多的代码原因pois不被任何声明。另外,如果您尝试从发布的大字符串中获取JSONObject s,则可以将该字符串传递给构造函数JSONObject mainObj = new JSONObject(jsonString),并为您创建该字符串。

话虽这么说,你可以走出mainObj如下:

JSONObject auth = mainObj.getJSONObject("authorization"); 
String hash = auth.getString("hash"); 
String salt = auth.getString("salt"); 

// To iterate over the location: 
JSONArray locations = mainObj.getJSONObject("walk").getJSONArray("locations"); 

for(int i = 0; i < locations.length(); i++) { 
    JSONObject locat = locations.getJSONObject(i); 

    String latitude = locat.getString("latitude"); 
    // Etc... 
}