无法在WCF REST中解析JSON数组

时间:2012-07-13 03:00:28

标签: c# json

这是我的JSON文件,其中包含多个“Application”对象:

{"Application":[{"appid":"0","appname":"application0"},
                {"appid":"1","appname":"application1"},
                ....
               ]} 

我从Android代码接收到我的WCF REST服务方法:

[WebInvoke(Method = "POST", UriTemplate = "/AcceptApp", RequestFormat = WebMessageFormat.Json,  
    ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
[OperationContract]
string AcceptApplication(Stream jsonstring);

这里是方法定义:

public string AcceptApplication(Stream inputStream)
{
    StreamReader r = new StreamReader(inputStream);
    string jsonstring = r.ReadToEnd();
    try
    {
       List<ApplicationEntity> list = JsonConvert.DeserializeObject<List<ApplicationEntity>>(jsonstring);
       for (int i = 0; i < list.Count; i++)
       {
         // using data
       }
    }
    catch (Exception E)
    {
        Logger.Error(E.Message);
    }

我的ApplicationEntity:

public class ApplicationEntity
{
    public string appid { get; set; }
    public string appname { get; set; }
} 

我正在获取jsonstring,但我收到了错误:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g.    
{"name":"value"}) into type  
'System.Collections.Generic.List`1[ApplicationEntity]' because the  
type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so
that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array 
or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type 
to force it to deserialize from a JSON object.

1 个答案:

答案 0 :(得分:2)

您尝试解析的JSON字符串不是列表或数组。它是一个具有名为"Application"的属性的对象,它是一个数组。 试试这个:

public class ApplicationObject
{
    public List<ApplicationEntity> Application { get; set; }
}
...
var apps = JsonConvert.DeserializeObject<ApplicationObject>(jsonstring);

现在您可以访问apps.Application上的列表。