无法在WCF REST中解析JSON数组 [英] Unable to parse JSON array in WCF REST

查看:122
本文介绍了无法在WCF REST中解析JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JSON文件,其中包含应用程序"的多个对象:

This is my JSON file that contains multiple objects of "Application":

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

我正在从Android代码中将其接收到WCF REST服务方法中:

I'm receiving it from Android code into my WCF REST service method:

[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:

My ApplicationEntity:

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

我正在获取jsonstring,但出现错误:

I'm getting jsonstring , but error I'm getting:

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.

推荐答案

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

The JSON string you are trying to parse is not a list or an array. It is an object with a property called "Application" that is an array. Try this:

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

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

Now you can access the list on apps.Application.

这篇关于无法在WCF REST中解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆