java - 反序列化 : get the data from the custom class

标签 java json gson

我正在尝试获取从 Web 服务获取的路线、方向、经度和纬度。我创建了 MapDataJSON 类以使用“Gson”库反序列化 json 字符串,但我不知道如何从 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;
        }
    }

}

最佳答案

只需更改您的代码以在下方进行阻止。您不需要 Map Data JSON 来包装项目。

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());
}

关于java - 反序列化 : get the data from the custom class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31240257/

相关文章:

java - 在自定义转换器中如何访问 EJB bean

java - 具有多个 id 的共享元素转换

java - 如何使用 Postman 中的 JSON 将值存储在特定列中(值由下划线_分隔)

javascript - 将 JSON 文件从数据库解析为 JavaScript 时出现问题

java - Map 子类的 Gson 序列化,也具有显式定义的属性

java - 如何使用一个对象中的多个属性并将其映射到另一个对象中的单个属性?

java - 我希望在单击 TextView 时出现的对话框中的 TextView 中显示数字

php - 如何使用 `vis.js`显示JSON数据

java - 根据 JSON 对象中的子值提取父名称。

java - 我将如何为可以处理动态字段的 Gson 对象建模?