Search code examples
web-servicesjson.netdeserializationjson-deserialization

How Deserialize JSON in C#


I would like to retrieve data from a restful web service in order to save this data into an object. The data retrieval works in principal and the JSON string can be shown in a text box. However, I struggle making the data usable in C# - after some research and own programming, I still get errors when deserialising that I am not able to fix:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft;
using System.IO;
using System.Net;

namespace Datenbankabfrage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, EventArgs e)
        {

            // Create a request for the URL. 
            WebRequest request = WebRequest.Create(
              "URL");
            // Get the response.
            WebResponse response = request.GetResponse();
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            Artikel ErsterA = new Artikel();

            Newtonsoft.Json.JsonConvert.PopulateObject(responseFromServer, ErsterA);

            //txtAusgabeAA.Text = responseFromServer;
            reader.Close();
            response.Close();
        }
    }
}

Here a picture of the error massage, which states:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException` occurred in Newtonsoft.Json.dll

Additional information: Cannot populate JSON array onto type 'Datenbankabfrage.Artikel'. Path ", line 1, position 1.

Any help is appreciated!


Solution

  • Your problem is explained by the exception message:

    Cannot populate JSON array onto type 'Datenbankabfrage.Artikel'. Path ", line 1, position 1.

    For background, JSON has two types of container:

    • An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

      Json.NET maps .NET IEnumerable, Lists, and Arrays (other than dictionaries) to JSON arrays.

    • An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).

      Json.NET maps non-enumerable .NET objects such as your Artikel to JSON objects.

    Thus from the exception it must be that the root container in your JSON string (not included in your question) is an array, and so cannot be populated onto a pre-existing non-enumerable POCO with JsonConvert.PopulateObject().

    Instead, the JSON needs to be deserialized as follows:

    var list = JsonConvert.DeserializeObject<List<Artikel>>(responseFromServer);