gpt4 book ai didi

java - 将输入流转换为 JSONArrary 时出现空异常

转载 作者:太空狗 更新时间:2023-10-29 15:17:24 24 4
gpt4 key购买 nike

我有一个 Android 应用程序,它尝试使用返回对象列表的 WCF 服务。流读取正确,但在尝试将字符串转换为 JSONArray 时抛出一个空的 JSONException。我在 JSON validator 上检查了 JSON 响应,这接缝没问题。

我的 WCF 服务契约(Contract):

   [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}] 类型 org.json.JSONArray 无法转换为 JSONObject

这表示使用 JSONArray,但再次抛出上述空异常。

希望有人能帮忙。


额外信息:此代码也抛出相同的异常:

String tekst = "[\"1\",\"2\"]";                         
JSONArray tenants = new JSONArray(tekst);

这是一个简单的 JSON 数组,我真的不明白为什么它不起作用。

最佳答案

我首先建议您更改框架中解析器的所有流监控代码,这样响应 block 将变为:

HttpResponse response = httpClient.execute(request);           
String tekst = EntityUtils.toString( response.getEntity() );

这可能有助于确保您从服务器获取所有正确的数据并正确格式化。这可能是您的读者拉低角色的方式。

关于java - 将输入流转换为 JSONArrary 时出现空异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11509195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com