JSON 使用 GSON 异常

JSON Exception using GSON

我正在使用发送 JSON 响应的 get API。我正在尝试使用 Gson 库将收到的 JSON 响应转换为 Java POJO,但它因 IllegalStateException 而失败。下面是带有代码的示例 JSON 响应。 数据是一个包含 StarEntity 对象列表的列表。

响应示例JSON

{ "signature":{"version":"1.0","source":"NASA/JPL Fireball Data API"},
          "count":3,
          "fields":["date","lat","lat-dir","lon","lon-dir","alt","vel","energy","impact-e"],
          "data":[
            ["2015-10-13 12:23:08","8.0","S","52.5","W","38.9",null,"2.3","0.082"],
            ["2015-10-11 00:07:46","55.4","S","18.8","W",null, null,"3.0","0.1"],
            ["2015-10-10 09:57:51","51.0","S","21.1","W","51.8",null,"3.6","0.12"]
          ]
        }

StarResponse 对象

  @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({ "signature", "count", "fields", "data" })
    public class StarResponse implements Serializable {
        
        private static final long serialVersionUID = 1L;
        Signature signatureObject;
         private float count;
         ArrayList < String > fields = new ArrayList < String > ();
         ArrayList <ArrayList< StarEntity >> data = new ArrayList <ArrayList< StarEntity >>();
    
    
         // Getter Methods 
    
         public Signature getSignature() {
          return signatureObject;
         }
    
         public float getCount() {
          return count;
         }
    
         // Setter Methods 
    
         public void setSignature(Signature signatureObject) {
          this.signatureObject = signatureObject;
         }
    
         public void setCount(float count) {
          this.count = count;
         }
    
        @Override
        public String toString() {
            return new ToStringBuilder(this).append("signature", signatureObject).append("count", count).append("fields", fields)
                    .append("data", data).toString();
        }
    
    }

星形实体

public class StarEntity {
    String date;
    String latitude;
    String latitudeDirection;
    String longitude;
    String longitudeDirection;
    String altitude;
    String velocity;
    String energy;
    String impact;
    
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getLatitude() {
        return latitude;
    }
    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }
    public String getLatitudeDirection() {
        return latitudeDirection;
    }
    public void setLatitudeDirection(String latitudeDirection) {
        this.latitudeDirection = latitudeDirection;
    }
    public String getLongitude() {
        return longitude;
    }
    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }
    public String getLongitudeDirection() {
        return longitudeDirection;
    }
    public void setLongitudeDirection(String longitudeDirection) {
        this.longitudeDirection = longitudeDirection;
    }
    public String getAltitude() {
        return altitude;
    }
    public void setAltitude(String altitude) {
        this.altitude = altitude;
    }
    public String getVelocity() {
        return velocity;
    }
    public void setVelocity(String velocity) {
        this.velocity = velocity;
    }
    public String getEnergy() {
        return energy;
    }
    public void setEnergy(String energy) {
        this.energy = energy;
    }
    public String getImpact() {
        return impact;
    }
    public void setImpact(String impact) {
        this.impact = impact;
    }

      @Override public String toString() { return
      date+" "+latitude+" "+latitudeDirection+" "+longitude+" "+longitudeDirection;
      }

HTTP 调用

public class HttpCall {
    static RestTemplate restTemplate = new RestTemplate();
    static String NasaResourceUrl = "https://ssd-api.jpl.nasa.gov/fireball.api?req-loc=true";
    
    public static void main(String []a) throws JsonMappingException, JsonProcessingException {
        ResponseEntity<String> response = restTemplate.getForEntity(NasaResourceUrl, String.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE,true);
        mapper.setVisibility(PropertyAccessor.FIELD,Visibility.ANY);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //String json = mapper.writeValueAsString(response.getBody());
        Gson gson = new Gson();
        System.out.println("Response Entity: "+response.getBody().toString()+"\n\n");
        //StarResponse starresponse = mapper.readValue(response.getBody(),  StarResponse.class);
        gson.fromJson(response.getBody(), StarResponse.class);
        //System.out.println(starresponse.toString());
    }
    
}

异常

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 176 path $.data[0][0]
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.read(ReflectiveTypeAdapterFactory.java:103)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
    at com.google.gson.Gson.fromJson(Gson.java:810)
    at com.google.gson.Gson.fromJson(Gson.java:775)
    at com.google.gson.Gson.fromJson(Gson.java:724)
    at com.google.gson.Gson.fromJson(Gson.java:696)
    at com.nasa.star.http.call.HttpCall.main(HttpCall.java:34)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 176 path $.data[0][0]
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:189)
    ... 13 more

您的 JSON 格式与您的 POJO 格式不匹配。根据您提供的 POJO,您的 JSON 应如下所示:

{
    "signature": {
        "version": "1.0",
        "source": "NASA/JPL Fireball Data API"
    },
    "count": 3,
    "fields": [
        "date",
        "lat",
        "lat-dir",
        "lon",
        "lon-dir",
        "alt",
        "vel",
        "energy",
        "impact-e"
    ],
    "data": [
        [
            {
                "date": "2015-10-13 12:23:08",
                "latitude": "8.0",
                "latitudeDirection": "S",
                "longitude": "52.5",
                "longitudeDirection": "W",
                "altitude": "38.9",
                "velocity": null,
                "energy": "2.3",
                "impact": "0.082"
            }
        ]
    ]
}