反序列化:从自定义类中获取数据

时间:2015-07-06 07:43:02

标签: java json gson

我正在尝试从网络服务中获取route, direction, longitude and latitude。我已经开始使用MapDataJSON类来使用'Gson'libraray对json字符串进行deserilaize,但我不知道如何从MapDataJSON对象获取数据。如何从MapDataJSSON类中获取数据route, direction, latitude and longitude

我感谢任何帮助。

Json字符串

[
  {
    "latitude": 20.123456,
    "longitude": 70.123456,
    "route": 4,
    "direction": "ABC"
   },

   {
    "latitude": 30.123456,
    "longitude": 80.123456,
    "route": 9,
    "direction": "DEF"
   },
     {
    "latitude": 10.123456,
    "longitude": 90.123456,
    "route": 3,
    "direction": "GHI"
   }

]

代码:

        Gson gson = new Gson();
        MapDataJSON[] data = gson.fromJson(sb.toString(),
                MapDataJSON[].class);

MapDataJSON类:

package com.json;

import java.util.ArrayList;

public class MapDataJSON {
    ArrayList<ItemDTO> items;

    public MapDataJSON(ArrayList<ItemDTO> items) {
        super();
        this.items = items;
    }

    public ArrayList<ItemDTO> getItems() {
        return items;
    }

    public void setItems(ArrayList<ItemDTO> items) {
        this.items = items;
    }

    public static class ItemDTO {
        double latitude;
        double longitude;
        int route;
        String direction;

        public ItemDTO(double latitude, double longitude, int route,
                String direction) {
            super();
            this.latitude = latitude;
            this.longitude = longitude;
            this.route = route;
            this.direction = direction;
        }

        public double getLatitude() {
            return latitude;
        }

        public double getLongitude() {
            return longitude;
        }

        public int getRoute() {
            return route;
        }

        public String getDirection() {
            return direction;
        }

        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }

        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }

        public void setRoute(int route) {
            this.route = route;
        }

        public void setDirection(String direction) {
            this.direction = direction;
        }
    }

}

1 个答案:

答案 0 :(得分:3)

只需将代码更改为阻止如下。你不需要MapDataJSON来包装物品。

Gson gson = new Gson();
Type listType = new TypeToken<List<ItemDTO>>() {}.getType();
List<ItemDTO> data = gson.fromJson(json, listType);

for (ItemDTO itemDTO : data) {
    System.out.print(itemDTO.getLatitude());
}