【问题标题】:Convert Java complex object to Json将 Java 复杂对象转换为 Json
【发布时间】:2011-11-30 19:45:07
【问题描述】:

我需要转换以下类:

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 的新手,需要帮助。 提前感谢您的帮助!

【问题讨论】:

    标签: java android json


    【解决方案1】:

    使用 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 你能帮帮我吗
    • @OnkarNene 你传递的数据太多了,你最好的办法是探索这个错误的原因,并尽量减少这样大块数据的出现,看这个帖子:@ 987654322@
    • @binnyb 谢谢你的回复,我会试试的。
    【解决方案2】:

    也可以使用 flexjson 序列化对象:http://flexjson.sourceforge.net/

    【讨论】:

    • 或 gson(我有很好的经验)或 jackson(我没有很好的经验)
    • Gson 也是一个可行的选择是的...... :)
    【解决方案3】:

    我认为使用累积是正确的。见:http://www.json.org/javadoc/org/json/JSONObject.html#accumulate(java.lang.String,%20java.lang.Object)

    但是您需要为每个 LatLon 创建一个 JSONObject,就像为 ExerciseSession 对象所做的一样。 然后,以下行是错误的: ExerciseSessionJSOBJ.accumulate("LatLons", l);

    “l”必须转换。

    【讨论】:

      【解决方案4】:

      我真的建议您避免使用 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 似乎是赢家。我对杰克逊一无所知,但这个实现似乎工作量太大而且过于复杂。
      • 我的示例比 GSON toJson/fromJson 方法更复杂的原因是,在 Android 上,许多应用程序在发布到市场之前都会经过一个混淆步骤。这意味着您不能依赖与其对应的 JSON 相同的变量名称。因此,您必须使用 @JsonProperty 进行注释并指定字段。您可以删除所有注释并让 Jackson 工作,但除非您传达变量映射信息,否则 Jackson 和 GSON 在混淆后都不会工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      相关资源
      最近更新 更多