用Jackson创建泽西岛的JsonArray

时间:2015-06-02 13:29:29

标签: java json jersey jackson

我正在使用泽西与杰克逊来处理JSON。在momenant我试图扭曲我的查询结果作为JSONArray。我想获得以下格式:

{
  "map_data":
             [
               {"route": 2, "latitude": 89.667781, "longitude": 13.517741},
               {"route": 7, "latitude": 89.657772, "longitude": 13.537742},
               {"route": 9, "latitude": 89.647763, "longitude": 13.547754},
               {"route": 12, "latitude":89.637754, "longitude": 13.567765}
              ]

}

杰克逊的格式怎么样?

数据库类中的

代码:

    if (busExist.next()) {
        for (int value : selected) {
            PreparedStatement preparedMap = con
                    .prepareStatement("SELECT route, latitude, longitude from bus where route= ?");
            preparedMap.setInt(1, value);
            ResultSet rsMap = preparedMap.executeQuery();
            while (rsMap.next()) {
                int route = rsMap.getInt("route");
                double lat = rsMap.getDouble("latitude");
                double lon = rsMap.getDouble("longitude");

            }

        }

    }

修改

    if (busExist.next()) {
        List<MapData> LRLHistory = new ArrayList<>();
        for (int value : selected) {
            PreparedStatement preparedMap = con
                    .prepareStatement("SELECT route, latitude, longitude from bus where route= ?");
            preparedMap.setInt(1, value);
            ResultSet rsMap = preparedMap.executeQuery();
            while (rsMap.next()) {
                int route = rsMap.getInt("route");
                double lat = rsMap.getDouble("latitude");
                double lon = rsMap.getDouble("longitude");

                MapData da_ma = new MapData(route, lat, lon);
                LRLHistory.add(da_ma);


            }

        }
        //System.out.println("The output of LRLHistory : "+LRLHistory);


    }

**编辑2:**

        Database db = new Database();
        List<MapData> lrl = db.get_map_data(selected);

        try {
            ObjectWriter ow = new ObjectMapper().writer()
                    .withDefaultPrettyPrinter();
            String json = ow.writeValueAsString(lrl);

            System.out.println("The output of json: " + json);
}

1 个答案:

答案 0 :(得分:0)

关于添加map_data字段,您可以在将容器Java对象序列化为json字符串之前添加它:

public static class MapDataHolder {
  List<MapData> mapDataList;

  public MapDataHolder(List<MapData> mapData) {
    this.mapDataList = mapData;
  }

  @JsonProperty("map_data") 
  public List<TestStuff.MapData> getMapData() {
    return mapDataList;
  }
}

MapDataHolder mapDataHolder = new MapDataHolder(lrl);
String json = ow.writeValueAsString(mapDataHolder);

The output of json: {
  "map_data" : [ {
    "route" : 1,
    "lat" : 1.1,
    "lon" : 1.2
  }, {
    "route" : 2,
    "lat" : 2.1,
    "lon" : 2.2
  } ]
}

当然,您可能需要相应地重命名(例如MapDataHolder - &gt; MapData,MapData - &gt; MapDataEntry)。