jsonarray文本必须以{{返回值}的字符1处的'['开头

时间:2011-01-29 22:41:48

标签: .net android web-services json rest

我是RESTFull WCF服务的新手,甚至更新的从Android应用程序调用它们。这是我的WCF服务:

[ServiceContract]
    public interface IPeople
    {
        [OperationContract]
        void DoWork();

        [WebGet(UriTemplate = "/GetPeople",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        [OperationContract]
        string GetPeople();
    }

接口的实现:

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

这就是我通过Android服务消费它的方式:

尝试{

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

我得到的例外是该主题中提到的内容。奇怪的是,在异常中返回的是期望值。我不知道为什么它期待方括号。

仅供参考,我使用的大部分代码都是直接来自在线示例。任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

您正在尝试从不包含有效JSON数组语法的字符串创建JSONArray。可以从[item1, item2, item3....]形式的字符串创建JSONArray,但您只需返回字符串中的单个项目:FirstName LastName

它之后的行只是返回缓冲区,所以无论如何JSONArray调用都没有意义。您根本不需要JSONArray调用,因为您没有处理JSON数据。只需删除该行。