gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:49:30 25 4
gpt4 key购买 nike

我是第一次使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com