无法将json解析为自定义对象列表

时间:2016-05-09 16:23:48

标签: c# json json.net deserialization

我正在尝试解析看起来像这样的json响应:

{
"response":
    {
    "status":"ok",
    "userTier":"developer",
    "total":12075,
    "startIndex":1,
    "pageSize":10,
    "currentPage":1,
    "pages":1208,
    "orderBy":"relevance",
    "results":[
        {
        "type":"article",
        "sectionId":"world",
        "webTitle":"Putin-themed cafe opens in Siberia",
        "webPublicationDate":"2016-04-13T14:56:42Z",
        "id":"world/2016/apr/13/vladimir-putin-themed-cafe-opens-in-siberia",
        "webUrl":"http://www.theguardian.com/world/2016/apr/13/vladimir-putin-themed-cafe-opens-in-siberia",
        "apiUrl":"http://content.guardianapis.com/world/2016/apr/13/vladimir-putin-themed-cafe-opens-in-siberia",
        "sectionName":"World news"
        },
        {
        "type":"article",
        "sectionId":"world",
        "webTitle":"Spain issues arrest warrants for Russian officials close to Putin",
        "webPublicationDate":"2016-05-04T16:59:27Z",
        "id":"world/2016/may/04/spain-issues-arrest-warrants-for-russian-officials-close-to-putin",
        "webUrl":"http://www.theguardian.com/world/2016/may/04/spain-issues-arrest-warrants-for-russian-officials-close-to-putin",
        "apiUrl":"http://content.guardianapis.com/world/2016/may/04/spain-issues-arrest-warrants-for-russian-officials-close-to-putin",
        "sectionName":"World news"
        }

我使用json2csharp.com创建了我的类(插入此字符串:http://content.guardianapis.com/search?q=putin&api-key=6392a258-3c53-4e76-87ec-e9092356fa74) 但是当我试图解析它时,我遇到了跟​​随错误:

var model = JsonConvert.DeserializeObject<List<NewsModel.RootObject>>(data);

实际上我以这种方式得到了我的数据:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://content.guardianapis.com/search?q=putin&api-key=6392a258-3c53-4e76-87ec-e9092356fa74");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
   Stream receiveStream = response.GetResponseStream();
   StreamReader readStream = null;

   if (response.CharacterSet == "")
       readStream = new StreamReader(receiveStream);
   else
       readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

       string data = readStream.ReadToEnd();
       DataSet ds = new DataSet();
       StringReader reader = new StringReader(data);

// parse here
}
  

json解析有些不好。消息:无法反序列化   当前的JSON对象(例如{“name”:“value”})到类型中   'System.Collections.Generic.List 1[sample.NewsModel+RootObject]' 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. Path 'response', line 1, position 12.Something bad with json parsing. Message: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List 1 [sample.NewsModel + RootObject]'   因为该类型需要一个JSON数组(例如[1,2,3])来反序列化   正确。要修复此错误,请将JSON更改为JSON数组   (例如[1,2,3])或更改反序列化类型以使其正常   .NET类型(例如,不是整数的基本类型,不是集合   类似于数组或List的类型,可以从JSON反序列化   宾语。 JsonObjectAttribute也可以添加到类型中以强制它   从JSON对象反序列化。路径'响应',第1行,位置   12。

2 个答案:

答案 0 :(得分:2)

看起来您正在尝试将响应反序列化为数组(响应将为[...])而不是单个对象(响应,如图所示,为{...})。将您的代码更改为:

var model = JsonConvert.DeserializeObject<NewsModel.RootObject>(data);

答案 1 :(得分:0)

试试这段代码。

using System.Net;

string requestUrl = String.Format("http://content.guardianapis.com/search?q=putin&api-key=6392a258-3c53-4e76-87ec-e9092356fa74");
string json = new WebClient().DownloadString(requestUrl);

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(json.ToString());
object result = dict["results"];

foreach (object items in result as System.Collections.ArrayList)
{
    Dictionary<string, object> item = (Dictionary<string, object>)items;
    string type = item["type"];
    string sectionId = item["sectionId"];
    ...
    ...
    ...
    //or
    //foreach(object item in items) { }
}