【发布时间】:2012-07-15 14:08:22
【问题描述】:
我有一个 Android 应用程序尝试使用返回对象列表的 WCF 服务。流读取正确,但在尝试将字符串转换为 JSONArray 时抛出空 JSONException。我在一个 JSON 验证器上检查了 JSON 响应,这个接缝没问题。
我的 WCF 服务合同:
[ServiceContract]
public interface IAndroidWebService
{
[OperationContract]
[WebGet(UriTemplate = "AndroidGetTenants",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
List<TenantEntity> AndroidGetTenants();
}
它被调用时生成的 JSON 响应:
[{"MaxVotesPerSecond":0,"Name":"Duurzaam OV","PartitionKey":"a63569b9-e794-4674-832b-46e85de0dc0a","RowKey":"02f1654c-9746-4da5-a146-bff7fe611468"},
{"MaxVotesPerSecond":0,"Name":"Overheid","PartitionKey":"e38f3d93-5b4d-41e9-8513-3fd350a019af","RowKey":"11ec2c3e-e65f-45cf-9c89-4aa40a2c21c7"}]
我的应用中使用的java代码:
HttpGet request = new HttpGet("http://XX.XX/WebService.svc/Android/AndroidGetTenants");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
byte[] buffer = new byte[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
stream.read(buffer);
stream.close();
String tekst = new String(buffer,"UTF-8");
JSONArray tenants = new JSONArray(tekst);
java 代码抛出一个空的 JSONException(catch 中的参数 e 不存在)。该服务似乎返回了一个对象数组。 当我改变时:
JSONArray tenants = new JSONArray(tekst);
与
JSONObject tenants = new JSONObject(tekst);
代码抛出JSONException: Value [{"RowKey":"02f1654c-9746-4da5 ...... esPerSecond":0}] of type org.json.JSONArray cannot be converted to JSONObject
这表明使用JSONArray,但这又抛出了上面提到的空异常。
希望有人能提供帮助。
额外信息: 这段代码也抛出了同样的异常:
String tekst = "[\"1\",\"2\"]";
JSONArray tenants = new JSONArray(tekst);
这是一个简单的 JSON 数组,我真的不明白为什么这不起作用。
【问题讨论】:
-
那是 JSON应该从服务器上下来吗,还是您在尝试创建
JSONArray之前注销了tekst的值? -
这是来自服务的实际 JSON。我认为代码是正确的,但是我的 SDK 中存在某种问题。完全重新安装了我的系统(包括 Windows 7),但仍然是同样的问题。
标签: java android json wcf arrays