我已经看到过类似的问题,但是在PHP和C#中,我的问题是我是java网络服务的新手,我们正在使用GSON对结果进行序列化,结果在ArrayList中,我的问题是我的android代码中的响应获取了GSON,但包装在HTML中,因此Gson()。fromJSon给出了错误。我需要删除HTML

这是我的代码,请帮忙。

@WebService()
public class Oracle_conexion {

private static final String driver = "oracle.jdbc.driver.OracleDriver";
private static final String database = "jdbc:oracle:thin:@XXX.xxxx.XX:1521:XE";
private static final String usuario = "web";
private static final String password = "prueba";
private static String resultado;

@WebMethod(operationName = "getListaClientes")
public static String getListaClientes() throws SQLException {
    List<Cliente> listaClientes = new ArrayList<Cliente>();

    Connection conn = null;
    PreparedStatement preparedStatement = null;

    String query = "SELECT * FROM xxxx.CLIENTES";

    try {
        conn = conexionbd();
        preparedStatement = conn.prepareStatement(query);
        ResultSet rs = preparedStatement.executeQuery();

        // Recorre el cursor

        while (rs.next()) {

            Cliente cliente = new Cliente();
            cliente.setNombre(rs.getString("NOMBRE"));
            cliente.setCodCliente(rs.getInt("CODIGO"));
            cliente.setCodComp(rs.getString("ORG"));

            listaClientes.add(cliente);
        }// while

    } catch (SQLException e) {
        System.out.println(e.getMessage());
    } finally {

        if (preparedStatement != null)
            preparedStatement.close();

        if (conn != null)
            conn.close();
    }
    JsonArray jsonarray = null;
    String json = "";
    try {
        if (listaClientes != null) {
            // json = new Gson().toJson(listaClientes);
            /*
             * Gson g = new Gson(); Type type = new
             * TypeToken<ArrayList<Cliente>>(){}.getType(); json =
             * g.toJson(listaClientes, type);
             */

            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(listaClientes,
                    new TypeToken<List<Cliente>>() {
                    }.getType());

            jsonarray = element.getAsJsonArray();

            /*
             * JsonObject jo = new JsonObject(); jo.add("j", new
             * JsonArray());
             */
            // Gson gson = new GsonBuilder().create();
            // jsonarray = gson.toJsonTree(listaClientes).getAsJsonArray();
            // json = new Gson().toJson(listaClientes);
        }

    } catch (Exception e) {
        System.out.println(e.getCause().getMessage());
    }

    // return listaClientes.toString();
    return jsonarray.toString();
}


这是我的android代码

public class CallSoap {

public String getListaCliente(){
    //ArrayList<Cliente> listaClientes = new ArrayList<Cliente>();
    String SOAP_ACTION = "http://oraclecon.com/getListaClientes";
    String OPERATION_NAME = "getListaClientes";
    String WSDL_TARGET_NAMESPACE = "http://oraclecon.com";

    String SOAP_ADDRESS="http://XXX.xxxx.XX:8088/OracleEclipWS/services/Oracle_conexion?wsdl";

    // Modelo el request
    SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

    envelope.dotNet = false;
    envelope.setOutputSoapObject(request);


    String response=null;
    //Para acceder al WS se crea un objeto de tipo HttpTransportSE , esto es propio de la libreria KSoap
    try {
        // Modelo el transporte
        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
        //httpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        httpTransport.debug = true;

        //Llamado al servicio web . Son el nombre del SoapAction, que se encuentra en la documentacion del servicio web y el objeto envelope
        httpTransport.call(SOAP_ACTION, envelope);
        /*HttpClient hc = new DefaultHttpClient();
        HttpGet get = new HttpGet(SOAP_ADDRESS);
        HttpResponse rp = hc.execute(get);
        HttpEntity entity = rp.getEntity();
        response = rp.toString();*/
        //Respuesta del Servicio web
        response = httpTransport.responseDump;

        /*for (int i=0;i<inpList.size();i++) {
          Cliente x = inpList.get(i);
          //System.out.println(x);
        }*/
         /*Gson gson = new GsonBuilder().create();
         TypeToken<List<Cliente>> token = new TypeToken<List<Cliente>>(){};
         List<Cliente> cli = gson.fromJson(response, token.getType());
         listaClientes = (ArrayList<Cliente>) cli;*/
    }catch (Exception ex){
        response=ex.getMessage();
    }

    return response;
}


这是我在mainactivity中的测试应用程序中的异步代码

public class MainActivity extends Activity {

public class AsyncCallSoapListaCli extends AsyncTask<String, Void, String> {
    // private final ProgressDialog dialog = new
    // ProgressDialog(MainActivity.this);

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        CallSoap CS = new CallSoap();
        String response = CS.getListaCliente();
        return response;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        Gson gson = new Gson();
        /*
         * Cliente[] listaCli = gson.fromJson(result, Cliente[].class);
         * List<Cliente> list = Arrays.asList(listaCli); list = new
         * ArrayList(list);
         */
        txtCodigo.setText(result);
        // dialog.dismiss();
        // ArrayList<Cliente> inpList = new ArrayList<Cliente>();
        // Type type = new TypeToken<ArrayList<Cliente>>(){}.getType();
        List<Cliente> inpList2 = (List<Cliente>) new Gson().fromJson(
                result, Cliente.class);

        /*
         * Gson gson = new GsonBuilder().create(); Map<String, Cliente>
         * gsonResponse; //TypeToken<List<Cliente>> token = new
         * TypeToken<List<Cliente>>(){}; Type collectionType = new
         * TypeToken<Map<String, Cliente>>(){}.getType(); gsonResponse =
         * gson.fromJson(result, collectionType); List<Cliente> cli =
         * gson.fromJson(result, collectionType); listCli =
         * (ArrayList<Cliente>) cli; textClientes.setText(result);
         */
        textClientes.setText(inpList2.get(0).getNombre());
    }
}

最佳答案

如果问题仅在于处理包装在HTML中的GSON,则在发送到Gson()。fromJson()之前,您可以很好地处理响应字符串(除去HTML标签)。
您可以制作一个实现** Html.TagHandler **接口的通用类,并在那里处理HTML标记,然后按以下方式使用它

txtCodigo.setText(Html.fromHtml(result, null, new MyTagHandler()));// where MyTagHandler implements Html.TagHandler


您可以参考This tutorial来实现它。

07-24 09:44
查看更多