天天看點

java複雜對象轉json_将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 LatLons;

}

LatLon如下:

public class LatLon {

public String LatLonId;

public String Latitude;

public String Longitude;

public String ExerciseSessionId;

public String LLAveSpeed;

public String Distance;

}

是以Class 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的新手,需要幫助.

在此先感謝您的幫助!