我的 Android 应用程序需要使用以下 Java 从我的 WCF 服务中获取用户名数组,然后填充微调器。
JSONArray mtUsers = new JSONArray(new String(buffer));
但是当我收到以下错误时,它似乎正在获取 JSONObject,
Android JSONObject cannot be converted to JSONArray
返回的 JSON 如下所示,
{"GetUserNamesResult":[{"UserName":"Peyton"},{"UserName":"Drew"},{"UserName":"Brett"}]}
这是我服务中的代码,
接口(interface):
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "GetUserNames")]
IList<UserNames> GetUserNames();
和类:
public IList<UserNames> GetUserNames()
{
IList<UserNames> lstusernames = new List<UserNames>();
var usernames = from p in _db.Users
select p;
foreach (User singleUsernames in usernames)
{
UserNames a = new UserNames();
a.UserName = singleUsernames.UserName;
lstusernames.Add(a);
}
return lstusernames;
}
JSON 应该是什么样子,谁能看出我做错了什么???
与其在黑暗中摸索着返回字符串或字符串[],不如问问你们。
干杯,
迈克。
最佳答案
实际上您正在获取 jsonObject,第一个键“GetUserNamesResult”的值是 JSONArray。
所以这样做..
JSONObject jsonResponse = new JSONObject(new String(buffer));
JSONArray mtUsers = jsonResponse.getJSONArray("GetUserNamesResult");
关于android - JSONObject 无法转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8018931/