[英]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.如何在 C# 中将 JSON 反序列化为数组,我想创建具有 JSON 属性的图像。 My current JSON File looks like this...我当前的JSON 文件看起来像这样......
{
"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.我的 Form1 有一个 Picture1,我试图用 Newtonsoft.json 反序列化,但我不知道如何将我的 JSON 对象反序列化为数组。 (i am a beginner in development) (我是开发初学者)
This is my current Form1 Code这是我当前的 Form1 代码
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您可以尝试使用JObject
和JArray
来解析 JSON 文件
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您可以使用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:以下代码使用您的示例 JSON 并输出基于数组的输出:
ImageResult.cs: 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.