我需要转换以下类别:将Java复杂对象为JSON
package comS309.traxz.data;
import java.util.Collection;
import org.json.JSONException;
import org.json.JSONObject;
public class ExerciseSession {
public String DateCreated;
public String TotalTime;
public String CaloriesBurned;
public String AvgSpeed;
public String SessionName;
public String Distance;
public String SessionType;
public String UserId;
public Collection<LatLon> LatLons;
}
凡LatLon如下:
public class LatLon {
public String LatLonId;
public String Latitude;
public String Longitude;
public String ExerciseSessionId;
public String LLAveSpeed;
public String Distance;
}
因此该类ExerciseSession具有LatLon对象的集合。现在我需要将ExerciseSession类从java转换成Json格式并将其发送到我的服务器。
我在android操作系统上这样做,如果这很重要。
我目前的解决办法是这样的:
JSONObject ExerciseSessionJSOBJ = new JSONObject();
ExerciseSessionJSOBJ.put("DateCreated", this.DateCreated);
ExerciseSessionJSOBJ.put("TotalTime", this.TotalTime);
ExerciseSessionJSOBJ.put("CaloriesBurned", this.CaloriesBurned);
ExerciseSessionJSOBJ.put("AvgSpeed", this.AvgSpeed);
ExerciseSessionJSOBJ.put("SessionName", this.SessionName);
ExerciseSessionJSOBJ.put("Distance", this.Distance);
ExerciseSessionJSOBJ.put("SessionType", this.SessionType);
ExerciseSessionJSOBJ.put("UserId", this.UserId);
//add the collection
for(LatLon l: LatLons)
{
ExerciseSessionJSOBJ.accumulate("LatLons", l);
}
我不知道这是啥..我使用JSON新手和需要帮助。 在此先感谢您的帮助!
这很光滑,谢谢! – Aziz
嗨binnyb,m使用您提供的答案将复杂的对象转换为JSON。但我有一些运行时异常像'java.lang.StackOverflowError:堆栈大小8MB'和'android.os.TransactionTooLargeException'你可以帮我 –
@OnkarNene你传递太多的数据,你最好打赌是探索此错误的原因,并尝试减少这种大块数据的发生,看到这篇文章:http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception – binnyb