无法从START_OBJECT标记中反序列化java.util.ArrayList的实例。来自我的POJO?

时间:2014-01-15 21:40:50

标签: java android json jackson resttemplate

我想使用jackson和restTemplate

解析这样的Json
{
            "coord": {
            "lon": 145.766663,
            "lat": -16.91667
        },
        "sys": {
            "country": "AU",
            "sunrise": 1381952820,
            "sunset": 1381997847
        },
        "weather": [
            {
                "id": 803,
                "main": "Clouds",
                "description": "broken clouds",
                "icon": "04n"
            }
        ],
        "base": "global stations",
        "main": {
            "temp": 297.15,
            "pressure": 1015,
            "humidity": 88,
            "temp_min": 297.15,
            "temp_max": 297.15
        },
        "wind": {
            "speed": 2.1,
            "deg": 350
        },
        "rain": {
            "3h": 0
        },
        "clouds": {
            "all": 75
        },
        "dt": 1382022000,
        "id": 2172797,
        "name": "Cairns",
        "cod": 200
    }

它来自OpenWeather api here

这是我的班级:

@JsonIgnoreProperties(ignoreUnknown=true)

公共类WeatherResult {

 @JsonProperty("coord")
 private CoordAttribute coordAttributes;

 @JsonProperty("sys")
 private SysAttribute sysAttributes;

 @JsonProperty("weather")
 private Weather[] weatherArray;

 public Weather[] getWeatherArray() {
    return weatherArray;
}

public void setWeatherArray(Weather[] weatherArray) {
    this.weatherArray = weatherArray;
}

@JsonProperty("base")
 private String base;

 @JsonProperty("main")
 private MainAttribute mainAttributes;

 @JsonProperty("wind")
 private WindAttribute windAttributes;

 @JsonProperty("rain")
 private RainAttribute rainAttributes;

 @JsonProperty("clouds")
 private CloudsAttribute cloudsAttributes;

 public CoordAttribute getCoordAttributes() {
    return coordAttributes;
}

public void setCoordAttributes(CoordAttribute coordAttributes) {
    this.coordAttributes = coordAttributes;
}

public SysAttribute getSysAttributes() {
    return sysAttributes;
}

public void setSysAttributes(SysAttribute sysAttributes) {
    this.sysAttributes = sysAttributes;
}


public String getBase() {
    return base;
}

public void setBase(String base) {
    this.base = base;
}

public MainAttribute getMainAttributes() {
    return mainAttributes;
}

public void setMainAttributes(MainAttribute mainAttributes) {
    this.mainAttributes = mainAttributes;
}

public WindAttribute getWindAttributes() {
    return windAttributes;
}

public void setWindAttributes(WindAttribute windAttributes) {
    this.windAttributes = windAttributes;
}

public RainAttribute getRainAttributes() {
    return rainAttributes;
}

public void setRainAttributes(RainAttribute rainAttributes) {
    this.rainAttributes = rainAttributes;
}

public CloudsAttribute getCloudsAttributes() {
    return cloudsAttributes;
}

public void setCloudsAttributes(CloudsAttribute cloudsAttributes) {
    this.cloudsAttributes = cloudsAttributes;
}

@JsonProperty("dt")
 private long dt;

 @JsonProperty("id")
 private long id;

 @JsonProperty("name")
 private String name;

 @JsonProperty("cod")
 private String cod;


public long getDt() {
    return dt;
}

public void setDt(long dt) {
    this.dt = dt;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getCod() {
    return cod;
}

public void setCod(String cod) {
    this.cod = cod;
}



 public class CoordAttribute {
     @JsonProperty("lon")
     private double lon;

     @JsonProperty("lat")
     private double lat;
     public double getLon() {
         return lon;
     }

     public void setLon(double lon) {
         this.lon = lon;
     }

     public double getLat() {
         return lat;
     }

     public void setLat(double lat) {
         this.lat = lat;
     }

 }

 public class SysAttribute {

     @JsonProperty("message")
     private String message;
     public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @JsonProperty("country")
     private String country;

     @JsonProperty("sunrise")
     private String sunrise;

     @JsonProperty("sunset")
     private String sunset;

     public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getSunrise() {
        return sunrise;
    }

    public void setSunrise(String sunrise) {
        this.sunrise = sunrise;
    }

    public String getSunset() {
        return sunset;
    }

    public void setSunset(String sunset) {
        this.sunset = sunset;
    }

 }

 public class Weather {
     @JsonProperty("id")
     private String idWeather;

     @JsonProperty("main")
     private String mainWeather;

     @JsonProperty("description")
     private String descriptionWeather;

     @JsonProperty("icon")
     private String iconWeather;

    public String getIdWeather() {
        return idWeather;
    }

    public void setIdWeather(String idWeather) {
        this.idWeather = idWeather;
    }

    public String getMainWeather() {
        return mainWeather;
    }

    public void setMainWeather(String mainWeather) {
        this.mainWeather = mainWeather;
    }

    public String getDescriptionWeather() {
        return descriptionWeather;
    }

    public void setDescriptionWeather(String descriptionWeather) {
        this.descriptionWeather = descriptionWeather;
    }

    public String getIconWeather() {
        return iconWeather;
    }

    public void setIconWeather(String iconWeather) {
        this.iconWeather = iconWeather;
    }
 }

 public class WindAttribute {
     @JsonProperty("speed")
     private double speed;

     @JsonProperty("deg")
     private double deg;

     public double getSpeed() {
         return speed;
     }

     public void setSpeed(double speed) {
         this.speed = speed;
     }

     public double getDeg() {
         return deg;
     }

     public void setDeg(double deg) {
         this.deg = deg;
     }


 }

 public class RainAttribute {
     @JsonProperty("3h")
     private double rainTruc;

    public double getRainTruc() {
        return rainTruc;
    }

    public void setRainTruc(double rainTruc) {
        this.rainTruc = rainTruc;
    }

 }

 public class MainAttribute {
     @JsonProperty("temp")
     private double temp;

     @JsonProperty("pressure")
     private double pressure;

     @JsonProperty("humidity")
     private double humidity;

     @JsonProperty("temp_min")
     private double tempMin;

     @JsonProperty("temp_max")
     private double tempMax;

     public double getTemp() {
        return temp;
    }

    public void setTemp(double temp) {
        this.temp = temp;
    }

    public double getPressure() {
        return pressure;
    }

    public void setPressure(double pressure) {
        this.pressure = pressure;
    }

    public double getHumidity() {
        return humidity;
    }

    public void setHumidity(double humidity) {
        this.humidity = humidity;
    }

    public double getTempMin() {
        return tempMin;
    }

    public void setTempMin(double tempMin) {
        this.tempMin = tempMin;
    }

    public double getTempMax() {
        return tempMax;
    }

    public void setTempMax(double tempMax) {
        this.tempMax = tempMax;
    }

 }

 public class CloudsAttribute {
     @JsonProperty("all")
     private double cloudsTruc;

    public double getCloudsTruc() {
        return cloudsTruc;
    }

    public void setCloudsTruc(double cloudsTruc) {
        this.cloudsTruc = cloudsTruc;
    }

 }

}

抱歉,这很长,因为所有的吸气者/制定者!

这是我的AsyncTask

public class WeatherAsyncTask extends AsyncTask<String, Void, Void> implements IParameters{

IResultsListener listener;

public void setOnResultsListener(IResultsListener listener) {
    this.listener = listener;
}

private WeatherResult weather = new WeatherResult();

@Override
protected Void doInBackground(String... params) {

    String city = params[0];

    URI url = UriComponentsBuilder.fromUriString(API_URL).path("/data/2.5/weather?q=").queryParam("city", city).build().toUri();
    //String url = "http://api.openweathermap.org/data/2.5/weather?q=Paris,fr&lang=fr";
    Log.d("url", url.toString());
    RestTemplate restTemplate = createJsonRestTemplate();

    HttpEntity<?> requestEntity = createJsonRequestEntity();

    try {
        ResponseEntity<WeatherResult> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, WeatherResult.class);

        HttpStatus statusCode = responseEntity.getStatusCode();

        if (statusCode == HttpStatus.OK) {
            weather = responseEntity.getBody();
        }

    } catch (HttpServerErrorException e) {
        e.printStackTrace();
    }

    return null;
}

@Override
// UI is managed here
protected void onPostExecute(Void result) {

    listener.onGetWeatherTaskSucceeded(weather);


}

private RestTemplate createJsonRestTemplate() {

    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate();

    // Add the Jackson message converter (JSON parser)
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    return restTemplate;
}

private HttpEntity<?> createJsonRequestEntity() {

    // Set the content-type headers
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));

    HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

    return requestEntity;
}

}

然后,它不起作用,这里是logcat!

01-15 22:54:26.226: E/AndroidRuntime(19086): FATAL EXCEPTION: AsyncTask #1
01-15 22:54:26.226: E/AndroidRuntime(19086): Process: com.example.applimeteo, PID: 19086
01-15 22:54:26.226: E/AndroidRuntime(19086): java.lang.RuntimeException: An error occured while executing doInBackground()
01-15 22:54:26.226: E/AndroidRuntime(19086):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at java.lang.Thread.run(Thread.java:841)
01-15 22:54:26.226: E/AndroidRuntime(19086): Caused by: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: No suitable constructor found for type [simple type, class com.example.applimeteo.WeatherResult$Weather]: can not instantiate from JSON object (need to add/enable type information?)
01-15 22:54:26.226: E/AndroidRuntime(19086):  at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41f4ac50; line: 1, column: 141] (through reference chain: com.example.applimeteo.WeatherResult["weather"]); nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.example.applimeteo.WeatherResult$Weather]: can not instantiate from JSON object (need to add/enable type information?)
01-15 22:54:26.226: E/AndroidRuntime(19086):  at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41f4ac50; line: 1, column: 141] (through reference chain: com.example.applimeteo.WeatherResult["weather"])
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:125)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:655)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:641)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:453)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:429)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at com.example.applimeteo.WeatherAsyncTask.doInBackground(WeatherAsyncTask.java:44)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at com.example.applimeteo.WeatherAsyncTask.doInBackground(WeatherAsyncTask.java:1)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-15 22:54:26.226: E/AndroidRuntime(19086):    ... 4 more
01-15 22:54:26.226: E/AndroidRuntime(19086): Caused by: org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.example.applimeteo.WeatherResult$Weather]: can not instantiate from JSON object (need to add/enable type information?)
01-15 22:54:26.226: E/AndroidRuntime(19086):  at [Source: com.android.okhttp.internal.http.HttpTransport$ChunkedInputStream@41f4ac50; line: 1, column: 141] (through reference chain: com.example.applimeteo.WeatherResult["weather"])
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:104)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:18)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
01-15 22:54:26.226: E/AndroidRuntime(19086):    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDe

谢谢你的帮助!

0 个答案:

没有答案