【问题标题】:How to convert one of my property of the JSON into an array?如何将我的 JSON 属性之一转换为数组?
【发布时间】:2018-05-04 16:47:09
【问题描述】:

如何将我的“威胁”转换为数组?

这是我的 JSON

[
    {
        "SensorType": "Visual",
        "Latitude": 1.3184418,
        "Longitude": 103.6282628,
        "Threat": [
            {
                "ThreatId": 56332,
                "Timestamp": "2018-05-02T13:15:43.6964862+08:00",
                "Latitude": 0,
                "Longitude": 0,
                "Bearing": 22.0,
                "FOV": 10.0,
                "ObjectId": "5320079"
            }
        ]
    }
]

这是我的 Java 文件

public class Threat {
    //public boolean IsNewDetection;
    public String SystemId;
    public String SystemName;
    public String SensorType;
    public Double Latitude;
    public Double Longitude;
    public ThreatTimeDetail Threat = new ThreatTimeDetail();

    public class ThreatTimeDetail {
        public Integer ThreatId;
        public Date Timestamp;
        public Double Latitude;
        public Double Longitude;
        public Float Bearing;
        public Float FOV;
        public String ObjectId;
    }
    public transient Date Timestamp;
    public transient Date mTimestamp;
    public transient boolean isUpdated;
}

这是我的请求威胁 Java 文件

bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
if (bufferedReader != null) {

    //not working
    Threat[] Sensorarray = new GsonBuilder()
                                .create()
                                .fromJson(bufferedReader, Threat[].class);
}

错误状态:由 java.lang.IllegalStateException 引起:应为 BEGIN_OBJECT 但在第 1 行第 80 列路径 $[0] 处为 BEGIN_ARRAY。威胁 在 com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)

如果我从 JSON 文件中删除“威胁:”之后的 [],它可以正常工作。

为什么会发生这种情况,我该如何解决?

【问题讨论】:

    标签: java android json gson


    【解决方案1】:

    这里的问题是你正在尝试从 Json 转换一个数组:

    [
      {
        ... ,
        "Threat": [ <<<<<<<<<<<<<
          {
            "ThreatId": 56332,
            "Timestamp": "2018-05-02T13:15:43.6964862+08:00",
            ... ,
            "ObjectId": "5320079"
          }
        ] <<<<<<<<<<<<<<
      }
    ]
    

    进入对象:

    public ThreatTimeDetail Threat = new ThreatTimeDetail();
    

    解决方案是创建一个数组而不是简单的对象:

    public ThreatTimeDetail[] Threat = new ThreatTimeDetail[50];
    

    【讨论】:

      【解决方案2】:

      您的Threat 字段定义应为:

          public ThreatTimeDetail[] Threat;
      

      您的 json 包含数组数据,但您映射到单个对象实例,因此引发了错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-06
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多