1

My Android application is expecting and array of usernames from my WCF Service using the following Java, to then populate a spinner.

JSONArray mtUsers = new JSONArray(new String(buffer));

But it seems to be getting a JSONObject as I get the following error,

Android JSONObject cannot be converted to JSONArray

The JSON that’s returned looks like this,

{"GetUserNamesResult":[{"UserName":"Peyton"},{"UserName":"Drew"},{"UserName":"Brett"}]}

This is the code in my service,

Interface:

[OperationContract]
[WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Wrapped,
    UriTemplate = "GetUserNames")]
IList<UserNames> GetUserNames();

And class:

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;
}

What should the JSON look like and can anyone see what I’m doing wrong???

Instead of stumbling around in the dark trying to return a string or string[], I thought I would ask you guys and gals.

Cheers,

Mike.

1 Answers1

9

actually you are getting jsonObject, the value of the first key "GetUserNamesResult" is JSONArray.

so do this..

JSONObject jsonResponse = new JSONObject(new String(buffer));
JSONArray mtUsers = jsonResponse.getJSONArray("GetUserNamesResult");
Yashwanth Kumar
  • 28,931
  • 15
  • 65
  • 69
  • 1
    Who hoo! Thanks, Yashwanth. That was the last thing I needed to do to get my first SQL Server, WCF Service to Android application going, I started on the whole undertaking 10 days ago and now it works! Now it’s on to best practices I guess, cleaning up that returned JSON, memory leaks, threads all the other things I’ve been reading about in the last 10 days. Can’t thank you enough, cheers, Mike. PS: love your gold star, maybe I can get one of those one day! –  Nov 05 '11 at 09:13