2014-04-15 29 views
0

我有一個我的類「Points」對象的數組,我想將它們放在JSONArray上,以前轉換爲JSONObject,但我遇到了一個我無法解決的問題,我無法解決把我的觀點[]放在JSONObject上,我不知道該怎麼做。我把代碼解釋得更好。將我的類投射到JSONObject

主要代碼:

JSONArray jsPoints = new JSONArray(); 
for(int i = 0; i < points.length; i++) 
{ 
    JSONObject js = new JSONObject(points[i]); 
    jsPoints.put(js); 
} 

Point類:

public class Point { 

String _id; 
String _comment; 
String _calification; 
String _coords; 
int _X; 
int _Y; 

public Point(String id, String comment, String calification, String coords, int x, int y) 
{ 
    _id = id; 
    _comment = comment; 
    _calification = calification; 
    _coords = coords; 
    _X = x; 
    _Y = y;  
} 
} 

值引入到類:

private void createPoints() 
{ 
    points = new Point[drawedInterestPoints.size()/2]; 
    int j = 0; 
    for(int i = 0; i < drawedInterestPoints.size() - 1; i++) 
    { 
     if(i % 2 == 0) 
     { 
      points[j] = new Point(pointType.get(i),comments.get(i),calification.get(i),GPScoords.get(i),drawedInterestPoints.get(i),drawedInterestPoints.get(i + 1)); 
      j++; 
     } 
    } 
} 

誰都可以高大的我,我必須做的,把每個我的點[]在JSONObject中,然後在JSONArray中?謝謝!

+1

這種方式有看看gson,找到你正在尋找的最好的圖書館 –

回答

0

嘗試使用GSON。這樣做:

Gson gson = new Gson(); 
final MyClass myClass = gson.fromJson(jsonString, MyClass.class); 

希望這有助於.. :)

+0

@Imrik>你解決了你的問題嗎? – Rashad

0

你不能直接投JSONArrayPoints

你可以這樣做以下

  1. GET JSON作爲字符串
  2. 將json反序列化爲使用jackson的點(ObjectMapper
0

在你的代碼

JSONObject js = new JSONObject(points[i]); 

沒有意義;你應該放點[]的每一個項目作爲jsObject標籤,然後在JsonArray

插入試試這個:

public void jsonAsStr() { 

    JSONObject mJsonObj = new JSONObject(); 

    try { 
     mJsonObj.put("tag1", true); 
     mJsonObj.put("tag2", 120); 
     mJsonObj.put("tag3", "Demo"); 

     JSONArray jsPoints = new JSONArray(); 
     jsPoints.put(mJsonObj); 

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

} 
0

你可以使用gson

Gson gson = new Gson(); 
Point point = new Point("", "", "", "", 1, 2); 
String json = gson.toJson(point);