如何将我的JSON属性转换为数组?

时间:2018-05-04 08:16:28

标签: java android json gson

如何转换我的"威胁"进入阵列?

这是我的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文件中,它工作正常。

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

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

您的Threat字段定义应为:

    public ThreatTimeDetail[] Threat;

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