2011-11-30 69 views
6

我需要转换以下类别:将Java复杂对象为JSON

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新手和需要帮助。 在此先感谢您的帮助!

回答

16

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

+0

这很光滑,谢谢! – Aziz

+0

嗨binnyb,m使用您提供的答案将复杂的对象转换为JSON。但我有一些运行时异常像'java.lang.StackOverflowError:堆栈大小8MB'和'android.os.TransactionTooLargeException'你可以帮我 –

+0

@OnkarNene你传递太多的数据,你最好打赌是探索此错误的原因,并尝试减少这种大块数据的发生,看到这篇文章:http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception – binnyb

2

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

+0

或GSON(我有很好的经验与)或杰克逊(我没有那么好与经验) – schlingel

+0

Gson也是一个可行的选择是... :) –

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变量。

这是起初有点混乱,但一旦你看着办吧节省了大量的时间。如果有什么不清楚,请告诉我。

+0

我的天生我很高兴我不使用杰克逊。对于像问题那样简单的事情,GSON似乎是胜利。我对杰克逊一无所知,但这种实现看起来像是太多的工作和过于复杂。 – binnyb

+3

我的示例比GSON toJson/fromJson方法更复杂的原因是,在Android上,很多应用程序在发布到市场之前都经过了混淆步骤。这意味着您不能依赖于变量名称与其JSON对应物保持相同。因此,您必须使用'@ JsonProperty'进行注释并指定字段。你可以删除所有的注释,但仍然有杰克逊的工作,但除非你传达变量映射信息,否则杰克逊和GSON都不会在混淆后工作。 – plowman