Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize an array of ints to send using KSOAP2

I'm having a problem trying to send an array of ints to a .NET web service which expects an array in one of the arguments. That's at least what I understand from the API description on the web service which says this:

<dataIndexIDs>
<int>int</int>
<int>int</int> </dataIndexIDs>

So when I send a single int like below I do not get any errors and I think it works fine.

request.addProperty("dataIndexIDs", 63);

But when I try to send an array of ints:

request.addProperty("dataIndexIDs", new int[] {63, 62}); // array of ints

or a ArrayList of Integers:

ArrayList<Integer> indexes = new ArrayList<Integer>();
    indexes.add(63);
    indexes.add(62);
    request.addProperty("dataIndexIDs", indexes); // ArrayList of Integers

I get thrown a "java.lang.RuntimeException: Cannot serialize" exception. Any help please? What am I doing wrong? Thanks!

like image 961
TomaszRykala Avatar asked Feb 09 '11 22:02

TomaszRykala


2 Answers

I'm sending from an Android client to a .NET server, this worked for me

SoapObject myArrayParameter = new SoapObject(NAMESPACE, MY_ARRAY_PARAM_NAME);
for( int i : myArray ) {
    PropertyInfo p = new PropertyInfo();
    p.setNamespace("http://schemas.microsoft.com/2003/10/Serialization/Arrays");
    // use whatever type the server is expecting here (eg. "int")
    p.setName("short");
    p.setValue(i);
    myArrayParameter.addProperty(p);
}
request.addSoapObject(myArrayParameter);

Produces

 <classificationIds>
     <n4:short i:type="d:long" xmlns:n4="http://schemas.microsoft.com/2003/10/Serialization/Arrays">18</n4:short>
 </classificationIds>

Which looks terrible, but the server eats it anyway

like image 132
user1691694 Avatar answered Sep 18 '22 02:09

user1691694


Here is nice example that might help you:

http://code.google.com/p/ksoap2-android/wiki/CodingTipsAndTricks

Here is my quick fix to this issue:

SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);

SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
soapEnvelope.setOutputSoapObject(Request);
soapEnvelope.dotNet = true;


List<Integer> companies =  new ArrayList<Integer>();
companies.add(65);
companies.add(66);
companies.add(67);

Request.addProperty("name", "test1");
SoapObject soapCompanies = new SoapObject(NAMESPACE, "companies");
for (Integer i : companies){
    soapCompanies.addProperty("int", i);
}
Request.addSoapObject(soapCompanies);

Output XML:

<n0:companies xmlns:n0 = "http://tempuri.org/">
            <int i:type = "d:int">65</int>
            <int i:type = "d:int">66</int>
            <int i:type = "d:int">67</int>
</n0:companies>
<name i:type = "d:string">test1</name>
like image 32
Mindaugas Jaraminas Avatar answered Sep 18 '22 02:09

Mindaugas Jaraminas