如何将类的名称公开给Gson对象?

时间:2015-01-09 11:00:49

标签: json gson

我有以下JSON数组:

[{avgSpeed: 39.43, customerId: 124, distance: 13.8, endDate: "2014-11-30T10:40:55Z",…},…]

其中

0: {avgSpeed: 39.43, customerId: 124, distance: 13.8, endDate: "2014-11-30T10:40:55Z",…}
1: {carId: 4942, currentMileage: 138903, dateOfPurchase: "16-????-2007", id: 124, initialMileage: 13,…}

我希望每个子字符串都命名为0 - Track,1 - MyCars,即:

0: {Track: {avgSpeed: 39.43, customerId: 124, distance: 13.8, endDate: "2014-11-30T10:40:55Z",…}}
1: {MyCars: {carId: 4942, currentMileage: 138903, dateOfPurchase: "16-????-2007", id: 124, initialMileage: 13,…})

如何实现这一目标?

我从Hibernate命名查询中提取Track和MyCars:

 <sql-query name="findAllPrivateTracks">
        <return alias="t" class="core.domain.track.Track"/>
        <return alias="xmc" class="core.domain.car.MyCars"/>
        <![CDATA[
                SELECT {t.*},
                       {xmc.*}
                  FROM edrive.Tracks t
                  JOIN edrive.Accounts a
                    ON a.Id = t.CustomerId
                  JOIN xxmycars xmc
                    ON xmc.id = t.customerId
                   AND xmc.ownerId = a.parentAccountId
                 WHERE a.ParentAccountId = :customerId
                 ORDER BY t.trackDate DESC
        ]]>
    </sql-query>

并在代码中:

List<?> result = (List<?>)session.getNamedQuery("findAllPrivateTracks")
                .setLong("customerId", customerId)
                .list();

我的变压器:

    List<?> list = trackDao.getTracksForCustomer(httpUtilities.getCustomerId());
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.setPrettyPrinting();
    builder.registerTypeAdapter(Track.class, new TrackTranslator());
    builder.registerTypeAdapter(MyCars.class, new MyCarsTranslator());
    Gson gson = builder.create();
    JsonElement je = gson.toJsonTree(list);
    String s = gson.toJson(list);

谢谢。

1 个答案:

答案 0 :(得分:0)

解决方案是使用Track和MyCars对的列表。

代码示例如下:

class Pair<Track,MyCars> {
    private final Track track;
    private final MyCars myCars;

    public Pair( Track track, MyCars myCars ) {
        this.track = track;
        this.myCars = myCars;
    }

    public Track getTrack() { return track; }
    public MyCars getMyCars() { return myCars; }

    @Override
    public int hashCode() { return track.hashCode() ^ myCars.hashCode(); }

    @Override
    public boolean equals(Object o) {
      if (o == null) return false;
      if (!(o instanceof Pair)) return false;
      Pair<?, ?> pairo = (Pair<?, ?>) o;
      return this.track.equals(pairo.getTrack()) &&
             this.myCars.equals(pairo.getMyCars());
    }
};    

从数据库返回的List的转换(它是Hibernate的Object []列表):

List<?> list = trackDao.getTracksForCustomer(httpUtilities.getCustomerId());

    List<Pair<Track,MyCars>> pairs = new ArrayList<>();
    Iterator<?> iterator = list.iterator();
    while ( iterator.hasNext() ) {
        Object[] tuple = (Object[]) iterator.next();
        pairs.add(new Pair<Track, MyCars>((Track) tuple[0],(MyCars) tuple[1]));
    }

return gson.toJson(pairs);

结果是:

0: {track:{avgSpeed:78.62, customerId:124, distance:806.53, endDate:2014-06-30T18:20:04Z,…},…}
>my_cars: {carId:4444, currentMileage:139000, dateOfPurchase:16-Nov-2007, id:124, initialMileage:13,…}
>track: {avgSpeed:78.62, customerId:124, distance:806.53, endDate:2014-06-30T18:20:04Z,…}