Web服务,JSON和Android。结果WS无法正常工作

时间:2012-03-08 19:34:28

标签: android json

我有这段代码:

    Carrera userRecived = null;
    HttpClient httpclient;
    HttpGet httpget;
    HttpResponse response;
    HttpEntity entity;
        /*Call Json service and Unserialize with Gson into the class*/
    try{
        httpclient = new DefaultHttpClient();

        httpget = new HttpGet(Url); 

        response = httpclient.execute(httpget);

        entity = response.getEntity();

            String result= EntityUtils.toString(entity);        

            Gson gson = new Gson();
            userRecived = gson.fromJson(result, Carrera.class);


    }catch(Exception error){throw new Error("Error en el get -- "+error.toString());}

我的问题是下一个错误: 03-08 19:07:42.899:E / AndroidRuntime(959):java.lang.Error:Error en el getcom.google.gson.JsonParseException:期望数组但找到对象:com.jorgechu.circuitlacostera.Objetos.Carrera@405852d0

我等待来自php webservice的结果,结果可能是下一个JSON:

[{"Codigo":"1","Denominacion":"Popular de Xativa","Imagen":"1231313","Poblacion":"Xativa","Lugar":"Valencia","Fecha":"11 de Noviembre de 2012","Hora":"17:00","Descripcion":"para probar","Reglamento":"http:\/\/www.google.es","Kilometros":"21"}]

我有一个Carrera对象存储此信息。

我希望有人帮助我。 谢谢。

2 个答案:

答案 0 :(得分:2)

你得到一个阵列,而不是一个物体。所以你必须做这样的事情:

Gson gson = new Gson();

Type collectionType = new TypeToken<Collection< Carrera >>(){}.getType();
List< Carrera > listOfObj= gson.fromJson(result, collectionType);

答案 1 :(得分:1)

变化:

userRecived = gson.fromJson(result, Carrera.class);

为:

List<Carrera> userRecived = (List<Carrera>) gson.fromJson(result, new TypeToken<List<Carrera>>(){}.getType());