如何在 C# 中反序列化 JSON

How Deserialize JSON in C#

我想从 restful 网络服务检索数据,以便将此数据保存到 object。数据检索工作正常,JSON 字符串可以显示在文本框中。但是,我很难使数据在 C# 中可用 - 经过一些研究和自己的编程,当 deserialising 我无法修复时,我仍然会遇到错误:

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,其中指出:

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.

感谢任何帮助!

异常消息解释了您的问题:

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

对于背景,JSON有两种类型的容器:

  • 数组是值的有序集合。数组以 [(左括号)开始,以 ](右括号)结束。值由 ,(逗号)分隔。

    Json.NET maps .NET IEnumerable、列表和数组(字典除外)到 JSON 数组。

  • 对象是 name/value 对的无序集合。对象以 {(左大括号)开始,以 }(右大括号)结束。

    Json.NET maps 不可枚举的 .NET 对象,例如您的 Artikel 到 JSON 对象。

因此,从例外情况来看,您的 JSON 字符串中的根容器(未包含在您的问题中)必须是一个数组,因此不能填充到预先存在的不可枚举的 POCO 上JsonConvert.PopulateObject().

相反,JSON 需要反序列化如下:

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