Convert Java complex objects to JSON
•
Java
I need to convert the following classes:
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 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 class exercisesession has a set of latlon objects Now I need to convert the exercisesession class from Java to JSON format and send it to my server
I do this on the Android operating system if it's important
My current solution is:
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'm not sure if it works I'm new to Jason and need help Thank you for your help!
Solution
It's easy to use Google's gson library This is an example:
Gson gson = new Gson(); String jsonRepresentation = gson.toJson(myComplexObject);
And get the object:
Gson gson = new Gson(); MyComplexObject myComplexObject = gson.fromJson(jsonRepresentation,MyComplexObject.class);
http://code.google.com/p/google-gson/
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码