【问题标题】:Unable to convert a json containing nested json arrays to an equivalent JAVA class using Gson无法使用 Gson 将包含嵌套 json 数组的 json 转换为等效的 JAVA 类
【发布时间】:2021-12-17 12:44:06
【问题描述】:

使用的 JSON 字符串:

'{"Sensors":[{\"name\":\"BLRB50CM_A\",\"cameraId\":\"Cam10\",\"id\":1,\"resolution\":\"1280 x 720\",\"officeLocation\":\"Offshore Development Center\",\"tags\":\"Entrance Camera, Parking Lot\",\"isActive\":\"true\",\"hls\":\"https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8\",\"rtsp\":\"rtsp://10.66.102.66:32278/mystream/parking_lot\",\"type\":\"sensor\",\"inputs\":[],\"outputs\":[2]}]}'

java pojo 类:

public class ServiceFlowData {

    public ArrayList<Sensor> sensors;
    
    public ArrayList<Sensor> getSensors() {
        return sensors;
    }

    public void setSensors(ArrayList<Sensor> sensors) {
        this.sensors = sensors;
    }
} 

用于转换为 java 对象的代码

Gson gson = new Gson();
ServiceFlowData serviceFlowData = gson.fromJson(jsonString,ServiceFlowData.class);
System.out.println("serviceFlowData"+serviceFlowData.getSensors());

我将获取传感器设为空。

我在这里错过了什么..?

【问题讨论】:

标签: java json string gson


【解决方案1】:

您的 json 键是 Sensors 而不是 sensors

解决方案 1

尝试改变

public ArrayList<Sensor> sensors;

public ArrayList<Sensor> Sensors;

解决方案 2

您可以使用@SerializedName注解将json键映射到具有不同名称的java变量。

【讨论】:

  • 这样做是个坏主意。 Gson 有一种特殊的方法可以将代码保留为 Java 代码约定。
  • @fluffy 更新了替代方案的答案。
猜你喜欢
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2014-07-18
  • 2021-06-22
相关资源
最近更新 更多