【发布时间】:2016-10-06 22:42:45
【问题描述】:
我是第一次使用 json,在互联网上搜索后,我找到了 JSON.NET。我认为它很容易使用,但我有一个问题。每次我使用代码时都会收到警告:
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“JSON_WEB_API.Machine”,因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。
这是来自 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; }
}
}
【问题讨论】:
-
试试
List<Machine> machines = JsonConvert.DeserializeObject<List<Machine>>(json);。您可以稍后迭代列表以访问各个Machine对象。
标签: c# arrays json json-deserialization