c# - 从 URL 使用 JSON.NET 反序列化 JSON 数组

标签 c# arrays json json-deserialization

我是第一次使用 json,在互联网上搜索后我找到了 JSON.NET。我认为它很容易使用,但我有一个问题。每次我使用代码时都会收到警告:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JSON_WEB_API.Machine' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

这是来自 URL 的 JSON 数组:

[
   {
      "id": "MachineTool 1",
      "guid": "not implemented",
      "name": "Individueller Maschinenname",
    },
    {
      "id": "MachineTool 2",
      "guid": "not implemented",
      "name": "Individueller Maschinenname",
    }
]

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace JSON_WEB_API
{
class Program
{
    static void Main()
    {
        string json = new WebClient().DownloadString("http://localhost:12084/Machines?format=json");
        Console.WriteLine(json);

        //string json = @"[{"id":"MachineTool 1","guid":"not implemented","name":"Individueller Maschinenname"},{"id":"MachineTool 2","guid":"not implemented","name":"Individueller Maschinenname"}]
        //Console.WriteLine(json)";

        Machine machine = JsonConvert.DeserializeObject<Machine>(json);
        Console.WriteLine(machine.id);

        Console.Read();
    }
}
[DataContract]
class Machine
{
    [DataMember]
    internal string id { get; set; }

    [DataMember]
    internal string guid { get; set; }

    [DataMember]
    internal string name { get; set; }
}

}

最佳答案

将其转换为机器列表

var machine = JsonConvert.DeserializeObject<List<Machine>>(json);

要访问数据,请在机器上运行 foreach。

foreach(var data in machine ) 
{ 
     Console.WriteLine(data.id); 
}

关于c# - 从 URL 使用 JSON.NET 反序列化 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37672423/

相关文章:

c# - 如何以线程安全的方式调用 .NET ConcurrentDictionary 上的 GetOrAdd 方法?

c++ - gdb - 如何查看指针数组的内容?

python - 仅从提到关键字的字符串中提取数字

javascript - 如何在动态生成的 HTML 表中停止递归

c# - 当分配给命令的连接处于挂起的本地传输时,ExecuteReader 要求命令具有事务

c# - 向面板添加垂直滚动条

c# - 如何在 Metro 应用程序中关闭 WebView

java - 制作 Swing Logo 测验

json - 使用 PUT 在一个请求中更新多个 JSON 数据

php - echo json 数据然后 sleep