JSON异常使用GSON

huangapple go评论149阅读模式
英文:

JSON Exception using GSON

问题

我正在调用一个获取API的方法,它会返回一个JSON响应。我尝试使用Gson库将接收到的JSON响应转换为Java的POJO对象,但是出现了IllegalStateException异常。以下是样本JSON响应和相关的代码部分。

样本响应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 {
    // ... (其他代码)
}

StarEntity对象

public class StarEntity {
    // ... (其他代码)
}

HTTP调用

public class HttpCall {
    // ... (其他代码)

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
        // ... (其他代码)

        Gson gson = new Gson();
        StarResponse starResponse = gson.fromJson(response.getBody(), StarResponse.class);
        // ... (其他代码)
    }
}

异常信息

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)
    // ... (其他异常信息)

希望这些信息对你有帮助。如果你还有其他问题,请随时提问。

英文:

I am consuming a get API which sends a JSON response. I am trying to convert the JSON response received to Java POJO using Gson library but it is failing with IllegalStateException. Below is the sample JSON response with the code.
Data is a list which holds list of StarEntity Object.

Sample response 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 Object

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

Star Entity

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 Call

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

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$1.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

答案1

得分: 1

您的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"
            }
        ]
    ]
}
英文:

Your JSON Format and your POJO format is mismatching. As per your POJO you provided, your JSON should look like below:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年8月14日 22:02:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63414279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定