7

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!

kamaci
  • 72,915
  • 69
  • 228
  • 366
Aziz
  • 1,584
  • 4
  • 23
  • 43

4 Answers4

17

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/

james
  • 26,141
  • 19
  • 95
  • 113
  • Hi binnyb, m converting complex object into JSON using the answer you provided. But i got some Runtime Exceptions like `java.lang.StackOverflowError: stack size 8MB` and `android.os.TransactionTooLargeException` Can u plz help me – Onkar Nene Nov 15 '16 at 10:09
  • @OnkarNene you're passing around too much data, you're best bet is to explore the cause for this error and try to reduce the occurrence of such large chunks of data, see this post: http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception – james Nov 15 '16 at 13:43
  • @binnyb Thanks for ua reply, i will try it. – Onkar Nene Nov 15 '16 at 14:09
2

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

Matjaz Muhic
  • 5,328
  • 2
  • 16
  • 34
1

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.

Alejandro Diaz
  • 431
  • 2
  • 9
1

I would really suggest you avoid using JSONObject to convert between Strings and Java objects. It will probably claim your sanity if you have to do too much of it. As an alternative, I'm a big fan of Jackson, which does what you describe in a really pleasant and simple way.

As a basic example,

public static class LatLon {

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

    @JsonCreator
    public LatLon(@JsonProperty("distance") String distance,
                  @JsonProperty("exerciseSessionId") String exerciseSessionId,
                  @JsonProperty("latitude") String latitude,
                  @JsonProperty("latLonId") String latLonId,
                  @JsonProperty("LLAveSpeed") String LLAveSpeed,
                  @JsonProperty("longitude") String longitude) {

        this.Distance = distance;
        this.ExerciseSessionId = exerciseSessionId;
        this.Latitude = latitude;
        this.LatLonId = latLonId;
        this.LLAveSpeed = LLAveSpeed;
        this.Longitude = longitude;
    }

    public static void something() {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"LLAveSpeed\":\"123\",\"Distance\":\"123\","
+ "\"ExerciseSessionId\":\"123\",\"LatLonId\":\"123\","
+ "\"Latitude\":\"123\",\"Longitude\":\"123\"}";

        try {
            //turn the json string into a LatLon object.
            LatLon latLon = mapper.readValue(json, LatLon.class);
            //turn the latLon object into a new JSON string
            String newJson = mapper.writeValueAsString(latLon);
            //confirm that the strings are equal
            Log.w("JacksonDemo", "Are they equal? " + json.equals(newJson));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This outputs Are they equal? true.

So you use readValue() to convert json to a Java object, writeValueAsString() to write an object back into json. @JsonCreator marks the constructor Jackson should use to convert betwee json and Java. @JsonProperty("jsonKeyName") marks the name of a variable in the json string and the Java variable it should map to.

This is a little confusing at first but saves a lot of time once you figure it out. Let me know if anything is unclear.

plowman
  • 13,335
  • 8
  • 53
  • 53
  • my goodness i'm glad i don't use Jackson. for something simple like the question asked, GSON seems to be the win. i don't know anything about Jackson, but this implementation seems like too much work and over-complicated. – james Nov 30 '11 at 20:14
  • 3
    The reason my example is more complicated than the GSON toJson/fromJson methods is that on Android, many apps go through an obfuscation step before being released to the market. This means that you cannot depend on variable names remaining the same as their JSON counterparts. As a result, you have to annotate with `@JsonProperty` and specify fields. You can remove all of the annotations and still have Jackson work, but neither Jackson nor GSON will work after obfuscation unless you convey variable mapping information. – plowman Nov 30 '11 at 20:22