Search code examples
c#arraysjsonjson-deserialization

Deserialize JSON Array with JSON.NET from URL


I am using json for the first time and after a search in the internet I found JSON.NET. I thought it is easy to use but I have a problem with it. Every time i use the code i get a warning:

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.

This is the JSON array from the URL:

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

And this is the CODE:

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; }
}

}

Solution

  • convert it to list of Machine

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

    To Access the Data run the foreach on machine.

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