从api“https://jsonplaceholder.typicode.com/posts”反序列化json字符串

时间:2018-06-13 06:29:30

标签: json-deserialization

我遇到了An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ConsoleApplication3.Program+UserData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

{
    class Program
    {


        public class UserData
        {
            public int userId { get; set; }
            public int id { get; set; }
            public string title { get; set; }
            public string body { get; set; }
        }

        static void Main(string[] args)
        {

            string url = @"https://jsonplaceholder.typicode.com/posts";

            WebRequest request = WebRequest.Create(url);

            WebResponse response = request.GetResponse();

            Stream data = response.GetResponseStream();

            StreamReader reader = new StreamReader(data);

            // json-formatted string from  api
            var responseFromServer = reader.ReadToEnd();

            UserData udata = JsonConvert.DeserializeObject<UserData>(responseFromServer);//getting error connot deserialize
        }


    }
}

1 个答案:

答案 0 :(得分:1)

我想你需要的是......

变化 UserData udata = JsonConvert.DeserializeObject<UserData>(responseFromServer);

UserData udata = JsonConvert.DeserializeObject<List<UserData>>(responseFromServer);

请注意<UserData> vs List<UserData>,这是唯一的变体。

你能试试吗?

编辑: 添加代码和rextester - http://rextester.com/IRUB82213

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {

            string responseFromServer = @"
                          [{
                            'userId': 1,
                            'id': 1,
                            'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
                            'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'
                          },
                          {
                            'userId': 1,
                            'id': 2,
                            'title': 'qui est esse',
                            'body': 'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla'
                          }]";


            var usersData = JsonConvert.DeserializeObject<List<UserData>>(responseFromServer);


            foreach(var userData in usersData){
                Console.WriteLine(userData.id);
            }
        }

        public class UserData
        {
            public int userId { get; set; }
            public int id { get; set; }
            public string title { get; set; }
            public string body { get; set; }
        }
    }
}