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; }
}
}
}
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());
}
}
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);
}
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.