android - JSONObject 无法转换为 JSONArray

标签 android wcf json

我的 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/

相关文章:

android - 使用 Twilio 视频流式传输 CustomView ARcore

wcf - 这是 Crudy 反模式吗?

c# - Unity 拦截器如何确定调用是来自 WCF 还是来自内部服务?

javascript - 对象、数组或类数组对象

javascript - Dart/Objective-C 和 Dart/Java 之间的交互

android - 如何验证多个复选框

c# - 我如何使用WCF服务而不是套接字客户端服务器应用程序?

arrays - Delphi-如何从字符串数组创建JSON数组?

javascript - Highcharts:解析多变量 JSON 数据

Android,自定义ListAdapter获取TextView-Text