C# 将 JSON 文件反序列化为数组
C# Deserialize a JSON File to Array
如何在 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"
}
]
}
我的 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; }
}
}
}
您可以使用 Newtoson Json.NET
轻松反序列化此类文件
您可以创建两个 类,它们将由该框架自动反序列化。例如。
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);
}
您可以尝试 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());
}
}
这对我有用。希望对你也有用。
首先,我创建了一个class。
public class ImageInfo
{
public string Url { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
而且,我做了这件事。
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);
我看到您正在反序列化为一个集合。如果你想要一个数组,试试
像这样:
以下代码使用您的示例 JSON 并输出基于数组的输出:
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();
}
}
使用代码:
var json = File.ReadAllText("ultra_hardcore_secret_file.json");
ImageResult result = ImageResult().FromJson(json);
如何在 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"
}
]
}
我的 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; }
}
}
}
您可以使用 Newtoson Json.NET
轻松反序列化此类文件您可以创建两个 类,它们将由该框架自动反序列化。例如。
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);
}
您可以尝试 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());
}
}
这对我有用。希望对你也有用。
首先,我创建了一个class。
public class ImageInfo
{
public string Url { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
而且,我做了这件事。
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);
我看到您正在反序列化为一个集合。如果你想要一个数组,试试 像这样:
以下代码使用您的示例 JSON 并输出基于数组的输出:
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();
}
}
使用代码:
var json = File.ReadAllText("ultra_hardcore_secret_file.json");
ImageResult result = ImageResult().FromJson(json);