将Java复杂对象转换为Json

7
我需要转换以下的类:
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;
}

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不熟悉,需要帮助。 非常感谢您提前的帮助!

4个回答

17

使用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/


嗨,binnyb,我正在使用你提供的答案将复杂对象转换为JSON。但是我遇到了一些运行时异常,例如java.lang.StackOverflowError: stack size 8MBandroid.os.TransactionTooLargeException。你能帮帮我吗? - Onkar Nene
@OnkarNene,你传递了太多的数据,最好的方法是探索这个错误的原因,并尝试减少这种大块数据的出现频率,请参考这篇文章:https://dev59.com/lmgu5IYBdhLWcg3wRlBh。 - james
@binnyb 感谢您的回复,我会尝试的。 - Onkar Nene

2

使用Gson(我有很好的经验)或Jackson(我没有那么好的经验)。 - schlingel
Gson也是一个可行的选择,是的... :) - Matjaz Muhic

1

1
我强烈建议您避免使用JSONObject在字符串和Java对象之间进行转换。如果您不得不频繁地这样做,它可能会让您失去理智。作为替代方案,我非常喜欢Jackson,它以一种非常愉悦和简单的方式完成了您所描述的工作。
作为一个基本示例,
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();
        }
    }
}

这将输出Are they equal? true

因此,您可以使用readValue()将json转换为Java对象,使用writeValueAsString()将对象写回json。@JsonCreator标记了Jackson应该用于在json和Java之间进行转换的构造函数。@JsonProperty("jsonKeyName")标记了json字符串中变量的名称以及它应该映射到的Java变量的名称。

一开始可能有点困惑,但一旦弄清楚了,就可以节省很多时间。如果有不清楚的地方,请告诉我。


我的天啊,我很高兴我不使用Jackson。对于像问题所问的简单事情,GSON似乎是胜利者。我不知道关于Jackson的任何事情,但这个实现看起来太麻烦和过于复杂了。 - james
3
我的例子比GSON的toJson/fromJson方法更加复杂的原因是,在Android上,许多应用在发布到市场之前都要经过混淆步骤。这意味着您不能依赖变量名与它们的JSON对应项保持相同。因此,您必须使用@JsonProperty注释并指定字段。您可以删除所有注释,并仍然使Jackson工作,但是在混淆之后,无论是Jackson还是GSON都不会工作,除非您传达变量映射信息。 - plowman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接