a jsonarray text must start with '[' at ch

2019-03-06 17:20发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-03-06 17:56

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.

查看更多
登录 后发表回答