将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;
}

所以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的新手,需要帮助.
在此先感谢您的帮助!

解决方法

使用Google的GSON库非常容易.这是一个使用示例:
Gson gson = new Gson();
String jsonRepresentation = gson.toJson(myComplexObject);

并获得对象:

Gson gson = new Gson();
MyComplexObject myComplexObject = gson.fromJson(jsonRepresentation,MyComplexObject.class);

http://code.google.com/p/google-gson/

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...