简体   繁体   English

使用KSOAP2库的WSDL / Soap Web服务响应复杂数组解析

[英]WSDL/Soap web service response complex array parsing using KSOAP2 library

I have created PHP web service using nusoap 我已经使用nusoap创建了PHP Web服务

$namespace="http:/mynamespace.com/mynamespace"
$server = new soap_server();
$server->debug_flag = false;
$server->configureWSDL("test", $namespace);
$server->wsdl->schemaTargetNamespace = $namespace;


$server->wsdl->addComplexType(
    'Products',
    'complexType',
    'struct',
    'all',
    '',
    array('ID' => array('name' => 'ID','type' => 'xsd:int'),
        'ProductName' => array('name' => 'ProductName','type' => 'xsd:string'),
        'ImageUrl' => array('name' => 'ImageUrl','type' => 'xsd:string')
        )
);

$server->wsdl->addComplexType(
    'ProductsArray',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(
    array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:Products[]')
    ),
    'tns:Products'
);
$server->register('GetProductDetails',                    // method name
  array('AgentId' => 'xsd:string'),          // input parameters
  array('return' => 'tns:ProductsArray'),    // output parameters
  $namespace,                         // namespace
  $namespace . '#GetProductDetails',                   // soapaction
  'rpc',                                    // style
  'sequence',                                // use
  'Get Product Details'        // documentation
);

function GetProductDetails($AgentId)
{
    $productArray = array();

    $sqlQry="SELECT pr.products_id, pr.products_image, pd.products_name FROM `products` pr left join products_description pd on pr.products_id=pd.products_id";
    $result=mysql_query($sqlQry);

    while($row=mysql_fetch_array($result)){
        $product=array();
        $product["ID"]=$row['products_id'];
    $product["ProductName"]=$row['products_name'];
    $product["ImageUrl"]=$row['products_image'];
        $productArray[]=$product;
    }
    return $productArray;
}
$HTTP_RAW_POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA'])?$GLOBALS['HTTP_RAW_POST_DATA'] : '';
$server->service($HTTP_RAW_POST_DATA);

and I am getting response in android something like 我在android中得到响应

[Products{ID=29; Name=product1; Url=product1.jpg; }, Products{ID=30; Name=product2; Url=product2.jpg; }]

this responce is in one element of response.getProperty(0) and if I paste this code in http://jsonviewer.stack.hu/ site then it tells me it is not valid json, I am new in nusoap so I don't know how this gives json/XML response Is there any problem with code? 此响应位于response.getProperty(0)一个元素中,如果我将此代码粘贴到http://jsonviewer.stack.hu/网站中,那么它会告诉我它不是有效的json,我是nusoap中的新手,所以我不不知道这如何给json / XML响应代码有问题吗? I have also tried Android Code: 我也尝试过Android代码:

 SoapObject response = (SoapObject) envelope.bodyIn;
 SoapObject nameResult = (SoapObject) response.getProperty(0);

In above nameResult I am getting all response in one single property. 在上面的nameResult我将在一个属性中获得所有响应。

I have never used nusoap before but from what I can tell your properly connecting to your db, and according to what i found nusoap can run standard php scripts in which case replaces function GetProductDetails with what i have below (I'm using json_encode), Your problem was with how you load a single result inside the while loop you must use array_push() instead. 我以前从未使用过nusoap,但是从我可以告诉您正确连接到数据库的角度来看,根据我发现nusoap可以运行标准php脚本,在这种情况下,我将下面的内容替换为功能GetProductDetails(我使用的是json_encode),您的问题在于,如何在while循环内加载单个结果,而必须使用array_push()。

function GetProductDetails($AgentId)
 {
  // array for JSON response
  $productArray = array();


 $sqlQry="SELECT pr.products_id, pr.products_image, pd.products_name FROM `products` pr      left join products_description pd on pr.products_id=pd.products_id";
  $result=mysql_query($sqlQry);

  while ($row = mysql_fetch_array($result)) {
    // temp user array
    $product=array();
    $product["ID"]=$row['products_id'];
    $product["ProductName"]=$row['products_name'];
    $product["ImageUrl"]=$row['products_image'];
    // push single product into final response array
    array_push($poductArray["products"], $product);
    }
// echoing JSON response
echo json_encode($productArray);
}

Hope this works it's clearly untested as I dont have your sql (but it's copied from similar script on my server and rewritten for your purposes) also you should cover the case your database is empty 希望它能正常工作,因为我没有您的sql(但是它是从服务器上的类似脚本复制并出于您的目的重写的),因此显然未经测试,还应该解决数据库为空的情况

I have solved it by my self, this is help here if any one needs how to solve this.. 我已经自己解决了,如果有人需要解决这个问题,这对您有帮助。

I am getting response is parsed using Vector and after that I just simply make a loop that get every attribute and add to ArrayList<HashMap<String, String>> . 我得到的响应是使用Vector解析的,此后,我只是简单地执行一个获取所有属性并添加到ArrayList<HashMap<String, String>>的循环。

My process is like, get response from webservice and parsing that response using vector and I just retrieve properties and add to ArrayList<HashMap<String, String>> . 我的过程就像从Web服务获取响应并使用vector解析该响应一样,我只是检索属性并将其添加到ArrayList<HashMap<String, String>>

So If here anyone wants to parse complexType Array Response and finds problem like me, they can find solution like following code 因此,如果这里有人想解析complexType Array Response并发现像我这样的问题,他们可以找到以下代码之类的解决方案

public static final ArrayList<HashMap<String, String>> productMapArray = new ArrayList<HashMap<String, String>>();

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;

        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        request.addProperty("user_id", "1");
   try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            Vector<SoapObject> response = (Vector<SoapObject>)envelope.getResponse();
            for (SoapObject soapObject : response) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(KEY_ID, soapObject.getProperty(KEY_ID).toString());
                map.put(KEY_PRODUCT, soapObject.getProperty(KEY_PRODUCT).toString());
                map.put(KEY_IMG, soapObject.getProperty(KEY_IMG).toString());
                productMapArray.add(map);
            }  
            if (response.toString().equalsIgnoreCase("invalid")) {
                result = false;
            } else {
                result = true;
            }

        } catch (SocketException ex) {
            result = false;
            Log.e("Error : ", "Error on soapPrimitiveData() " + ex.getMessage());
            ex.printStackTrace();
        } catch (Exception e) {
            result = false;
            Log.e("Error : ", "Error on soapPrimitiveData() " + e.getMessage());
            e.printStackTrace();
        }
        return result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM