通过JSON从Android到ASP.NET Web服务的用户定义对象列表

时间:2013-06-05 08:20:18

标签: android asp.net json json.net gson

我有一个用ASP.NET编写的Web服务,它接受类型联系人列表(列表)。

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    #region List of contacts that need to be created in the database.
    public List<KeyValue> createRecordsInDb(List<Contact> dataToPass)
    {
        return Contact.insertArrayIntoDb(dataToPass);
    } 
    #endregion

在Android设备上,我正在使用GSON库将列表转换为字符串

    List<Contact> lstContactsToCreate= retrieveDataFromCursor(cursor,false);
    String jsonString = new Gson().toJson(lstContactsToCreate);
    try {
        callWebService(jsonString, _context.getResources().getString(R.string.updateCreateURL), false);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {           
        e.printStackTrace();
    }

当我希望将数据发送到Web服务时,会出现问题。我通过以下方法传递数据,

private HttpResponse callWebService(String dataToPass, String URL, boolean isUpdate) 
        throws JSONException, ClientProtocolException, IOException{
    HttpPost httpPost = new HttpPost(URL);
    httpPost.setHeader("content-type", "application/json");

    HttpClient httpClient = new DefaultHttpClient(getHttpParameterObj(4000,4000));

    // Building the JSON object.
    JSONObject data = new JSONObject();
    data.put("dataToPass", dataToPass);

    StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8);

    entity.setContentType("application/json");
    entity.setContentEncoding( "UTF-8");

    httpPost.setEntity(entity);
    // Making the call.
    HttpResponse response = httpClient.execute(httpPost);
    return response;
}

每当我调用webservice时,它都会抛出以下错误 -

{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1

问题是data.toString()会返回: -

{"dataToPass":"[{\"address\":\"Himayath Nagar\",\"email\":\"abijeet.p@osmosys.asia\",\"name\":\"Abijeet Patro\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"himayath naga\",\"email\":\"saravana.e@osmosys.asia\",\"name\":\"Saravana\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"hellpo world\",\"email\":\"asshole@gmail.com\",\"name\":\"Syai\",\"server_id\":\"\",\"status\":\"\"}]"}

而webservice期望格式为

的数据
{"dataToPass":[{\"address\":\"Himayath Nagar\",\"email\":\"abijeet.p@osmosys.asia\",\"name\":\"Abijeet Patro\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"himayath naga\",\"email\":\"saravana.e@osmosys.asia\",\"name\":\"Saravana\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"hellpo world\",\"email\":\"asshole@gmail.com\",\"name\":\"Syai\",\"server_id\":\"\",\"status\":\"\"}]}

我甚至尝试更换和删除那些“”: -

data.toString().replace("\"[","[").replace("]\"","]");
     (java.lang.String) {"dataToPass":[{\"address\":\"Himayath Nagar\",\"email\":\"abijeet.p@osmosys.asia\",\"name\":\"Abijeet Patro\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"himayath naga\",\"email\":\"saravana.e@osmosys.asia\",\"name\":\"Saravana\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"hellpo world\",\"email\":\"asshole@gmail.com\",\"name\":\"Syai\",\"server_id\":\"\",\"status\":\"\"}]}

但是,由于Web服务器抛出错误

,这似乎不起作用
{"Message":"Invalid object passed in, member name expected. (16): {\"dataToPass\":[{\\\"address\\\":\\\"Himayath Nagar\\\",\\\"email\\\":\\\"abijeet.p@osmosys.asia\\\",\\\"name\\\":\\\"Abijeet Patro\\\",\\\"server_id\\\":\\\"\\\",\\\"status\\\":\\\"\\\"},{\\\"address\\\":\\\"himayath naga\\\",\\\"email\\\":\\\"saravana.e@osmosys.asia\\\",\\\"name\\\":\\\"Saravana\\\",\\\"server_id\\\":\\\"\\\",\\\"status\\\":\\\"\\\"},{\\\"address\\\":\\\"hellpo world\\\",\\\"email\\\":\\\"asshole@gmail.com\\\",\\\"name\\\":\\\"Syai\\\",\\\"server_id\\\":\\\"\\\",\\\"status\\\":\\\"\\\"}]}","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

那么如何将用户定义的对象数组从Java传递到ASP.NET Web服务?或者我可以将asp.net Web服务器上的GSON字符串转换为List对象吗?

我可以使用JSON.NET将字符串反序列化为我的列表吗?

1 个答案:

答案 0 :(得分:1)

link has an answer有效。我只是将服务器端的数据作为字符串,然后将其转换为我可以处理的数组。

示例JSON:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

类别:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

反序列化

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

可能不是最佳答案,因为我们可能无法始终访问Web服务器的代码。我会暂时离开这个。