0

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; }
        }
    }
}
5
  • You should try and put some effort into your question... the MyForm1 has an Picture1 part makes no sense. show us what you tried already... Commented Dec 4, 2019 at 12:42
  • You should have a look at Newtonsoft's Json.NET Commented Dec 4, 2019 at 12:45
  • Does this answer your question? Deserialize a JSON array in C# Commented Dec 4, 2019 at 12:47
  • do you want a sample of image serialize/desalinize ? or just a serialize/desalinize ? Commented Dec 4, 2019 at 12:52
  • The code that you have posted works exactly like it is as expected. What exactly is the issue that you're having? Commented Dec 4, 2019 at 12:59

4 Answers 4

8

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());
       }
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, that works, only, how exactly can i make sure that i leave only some values?
@user11332792, can you please elaborate on what you mean by some values?
what I mean is, my label1.text now returns the following values: url1.png url2.jpg url3.jpeg, but how can I achieve that I only get one value back? for example ... index [1] = url2.jpg
@user11332792m try jsonArray[0]["url"].ToString()
1

You can easily deserialize such file by using Newtoson Json.NET

You could create two classes that would be deserialized automatically by this framework. For example.

        public class ListImage
        {
            public List<Image> test;
        }

        public class Image
        {
            public string url;
            public string width;
            public string height;
        }

        static void Main(string[] args)
        {
            var fileContent = File.ReadAllText("path to your file");
            var deserializedListImage = JsonConvert.DeserializeObject<ListImage>(fileContent);
        }

5 Comments

How can i print this in a Label?
What exactly do you want to print?
If you want to print information from all items from the list, you gotta iterate through the list and just append every information of Image instance you want to print.
i would like to print the results, for example: "button1.Text = deserializedListImage.test.url" to print out a url from my json, Do you understand what I mean?
deserializedListImage.test is a List so you need to specify an index for the element. For example, if you want to print the first element from the list just return deserializedListImage.test[0].url.
0

This worked for me. I hope it works for you, too.

Firstly, I created a class.

public class ImageInfo
{
    public string Url { get; set; }
    public string Width { get; set; }
    public string Height { get; set; }
}

And, I did this things.

  string json = 
             @"[{
                'url':'150.png',
                'width':'300',
                'height':'300'
              },
              {
                'url':'150.png',
                'width':'300',
                'height':'300'
              },
              {
                'url':'150.png',
                'width':'300',
                'height':'300'
              }]";

   var strImageInfo = JsonConvert.DeserializeObject<IEnumerable<ImageInfo>>(json);

Comments

0

I see that you are deserializing into a collection. If you want an array, try something like this:

Following code uses your sample JSON and outputs an array-based output:

ImageResult.cs:

using System;
using System.Collections.Generic;

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace TestProject
{

    public partial class ImageResult
    {
        [JsonProperty("test", NullValueHandling = NullValueHandling.Ignore)]
        public Test[] Test { get; set; }
    }

    public partial class Test
    {
        [JsonProperty("url", NullValueHandling = NullValueHandling.Ignore)]
        public string Url { get; set; }

        [JsonProperty("width", NullValueHandling = NullValueHandling.Ignore)]
        [JsonConverter(typeof(ParseStringConverter))]
        public long? Width { get; set; }

        [JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)]
        [JsonConverter(typeof(ParseStringConverter))]
        public long? Height { get; set; }
    }

    public partial class ImageResult
    {
        public static ImageResult FromJson(string json) => JsonConvert.DeserializeObject<ImageResult>(json, TestProject.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this ImageResult self) => JsonConvert.SerializeObject(self, TestProject.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }

    internal class ParseStringConverter : JsonConverter
    {
        public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);

        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null) return null;
            var value = serializer.Deserialize<string>(reader);
            long l;
            if (Int64.TryParse(value, out l))
            {
                return l;
            }
            throw new Exception("Cannot unmarshal type long");
        }

        public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
        {
            if (untypedValue == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var value = (long)untypedValue;
            serializer.Serialize(writer, value.ToString());
            return;
        }

        public static readonly ParseStringConverter Singleton = new ParseStringConverter();
    }
}

To use the code:

var json = File.ReadAllText("ultra_hardcore_secret_file.json");
ImageResult result = ImageResult().FromJson(json);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.