0

I'm experiencing 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
        }


    }
}
Kalle Richter
  • 8,008
  • 26
  • 77
  • 177

1 Answers1

1

I guess what you need is ...

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

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

Notice <UserData> vs List<UserData>, that is the only variation.

Could you please try this?

EDIT : Adding code and rextester - http://rextester.com/IRUB82213

Code:

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; }
        }
    }
}
AD8
  • 2,168
  • 2
  • 16
  • 31
  • Ahan!!! Nice catch,we got as expected.The thing is that we are not attaining the whole data in list. Thanks For your help :) – Mani Pathak Jun 13 '18 at 08:08
  • @ManiPathak no worries bhai. Are you getting results as expected now? I couldn’t quite understood what you meant by ‘we are not attaining the whole data in list’. – AD8 Jun 13 '18 at 08:11
  • Cool happy coding :-) – AD8 Jun 13 '18 at 08:30