Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java complex object to Json

Tags:

java

json

android

I need to convert the following Class:

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

Where LatLon is as follows:

public class LatLon {

    public String LatLonId;
    public String Latitude;
    public String Longitude;
    public String ExerciseSessionId;
    public String LLAveSpeed;
    public String Distance;
}

So the Class ExerciseSession has a collection of LatLon objects. Now I need to convert The ExerciseSession Class into a Json format from java and send it to my server.

I am doing this on the android OS, if that matters.

My current solution is this:

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

I am not sure this is valid.. I am a novice with Json and need help. Thanks in advance for the help!

like image 372
Aziz Avatar asked Nov 30 '11 19:11

Aziz


3 Answers

This is very easy to do using Google's GSON library. Here's an example use:

Gson gson = new Gson();
String jsonRepresentation = gson.toJson(myComplexObject);

And to get the object back:

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

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

like image 182
james Avatar answered Oct 02 '22 13:10

james


You can also serialize the object using flexjson: http://flexjson.sourceforge.net/

like image 36
Matjaz Muhic Avatar answered Oct 02 '22 13:10

Matjaz Muhic


I think using the accumulate is correct. See: http://www.json.org/javadoc/org/json/JSONObject.html#accumulate(java.lang.String,%20java.lang.Object)

But you need to create a JSONObject for each LatLon as you do for the ExerciseSession object. Then, the following line is wrong: ExerciseSessionJSOBJ.accumulate("LatLons", l);

"l" must be transformed.

like image 38
Alejandro Diaz Avatar answered Oct 02 '22 12:10

Alejandro Diaz