use*_*792 0 c# serialization json converters toarray
如何在 C# 中将 JSON 反序列化为数组,我想创建具有 JSON 属性的图像。我当前的JSON 文件看起来像这样......
{
"test":[
{
"url":"150.png",
"width":"300",
"height":"300"
},
{
"url":"150.png",
"width":"300",
"height":"300"
},
{
"url":"150.png",
"width":"300",
"height":"300"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我的 Form1 有一个 Picture1,我试图用 Newtonsoft.json 反序列化,但我不知道如何将我的 JSON 对象反序列化为数组。(我是开发初学者)
这是我当前的 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; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以尝试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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4461 次 |
| 最近记录: |