Search code examples
c#jsonserializationconverterstoarray

C# Deserialize a JSON File to Array


How can i Deserialize a JSON to Array in C#, i would like to create Images with JSON Attributes. My current JSON File looks like this...

{
  "test":[
    {
      "url":"150.png",
      "width":"300",
      "height":"300"
    },
    {
      "url":"150.png",
      "width":"300",
      "height":"300"
    },
    {
      "url":"150.png",
      "width":"300",
      "height":"300"
    }
  ]
}

My Form1 has an Picture1 I tried to Deserialize with Newtonsoft.json but i dont know how i can Deserialize my JSON Objects to an Array. (i am a beginner in development)

This is my current Form1 Code

using System;
using System.Windows.Forms;
using System.Collections.Generic;

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Linq;
using System.Drawing;

namespace viewer_mvc
{

    public partial class Index : Form
    {
        string url;
        int width, height;

        public Index()
        {
            InitializeComponent();
        }

        private void Index_Load(object sender, EventArgs e)
        {
            /*using (StreamReader file = File.OpenText("ultra_hardcore_secret_file.json"))
            {
                JsonSerializer serializer = new JsonSerializer();
                Elements img = (Elements)serializer.Deserialize(file, typeof(Elements));

                url = "../../Resources/" + img.url;
                width = img.width;
                height = img.height;
            }

            pictureBox1.Image = Image.FromFile(url);
            pictureBox1.Size = new Size(width, height);*/
            var json = File.ReadAllText("ultra_hardcore_secret_file.json");
            RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);

            button1.Text = obj.test.ToString();

        }


        public class Elements
        {
            public string url { get; set; }
            public string width { get; set; }
            public string height { get; set; }
        }
        public class RootObject
        {
            public List<Elements> test { get; set; }
        }
    }
}

Solution

  • You can try JObject and JArray to parse the JSON file

    using (StreamReader r = new StreamReader(filepath))
    {
           string jsonstring = r.ReadToEnd();
           JObject obj = JObject.Parse(jsonstring);
           var jsonArray = JArray.Parse(obj["test"].ToString());
    
           //to get first value
           Console.WriteLine(jsonArray[0]["url"].ToString());
    
           //iterate all values in array
           foreach(var jToken in jsonArray)
           {
                  Console.WriteLine(jToken["url"].ToString());
           }
    }