a jsonarray text must start with '[' at character 1 of {my returned value}

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

I'm very new to RESTFull WCF Services and even newer to calling them from an Android app. Here's my WCF service:

[ServiceContract]     public interface IPeople     {         [OperationContract]         void DoWork();          [WebGet(UriTemplate = "/GetPeople",             BodyStyle = WebMessageBodyStyle.WrappedRequest,             ResponseFormat = WebMessageFormat.Json,             RequestFormat = WebMessageFormat.Json)]         [OperationContract]         string GetPeople();     } 

The implementation of the interface:

public string GetPeople() { PeoplesEntities qe = new PeoplesEntities();

             var result = from q in qe.tPeople                           select q;                int count = result.Count();              int index = new Random().Next(count);               tPeople people = result.OrderBy(a=>a.ID).Skip(index).FirstOrDefault();               // result.First().ToString();                return people.FirstName + " - " + people.LastName;      } 

and this is how i'm consuming it through an android service:

try {

       HttpGet request = new HttpGet(SERVICE_URI + "/GetPeople");        request.setHeader("Accept", "application/json");        request.setHeader("Content-type", "application/json");         DefaultHttpClient httpClient = new DefaultHttpClient();        HttpResponse response = httpClient.execute(request);         HttpEntity responseEntity = response.getEntity();         // Read response data into buffer        char[] buffer = new char[(int)responseEntity.getContentLength()];        InputStream stream = responseEntity.getContent();        InputStreamReader reader = new InputStreamReader(stream);        reader.read(buffer);        stream.close();         JSONArray plates = new JSONArray(new String(buffer));                return new String(buffer);       } catch (Exception e) {        e.printStackTrace();        return e.toString();    } } 

The exception I get is what is mentioned in the subject. What's strange is the value tha ti'm expecting is returned in the exception. I have no clue why it's expecting the square bracket.

FYI, most of the code i used is taken directly from online examples. Any help would be greatly appreciated. Thanks.

回答1:

You're trying to create a JSONArray from a string that doesn't contain valid JSON array syntax. A JSONArray can be created from a string of the form [item1, item2, item3....] but you're just returning a single item in your string: FirstName LastName.

The line after it just returns the buffer, so the JSONArray call is pointless, anyway. You don't need the JSONArray call at all, since you're not dealing with JSON data. Just remove that line.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!