在c#中反序列化JSON数据的好方法,但很简单
本文关键字:方法 简单 反序列化 JSON 数据 | 更新日期: 2023-09-27 18:27:43
我已经挣扎了很长一段时间,但现在我成功地从web API中提取了JSON数据。
到目前为止我的代码(到目前为止只是一个测试片段):
var url = "http://www.trola.si/bavarski";
string text;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
var json = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(json.GetResponseStream()))
{
text = sr.ReadToEnd();
}
就提取数据而言,这是可以的,对吧?
这就是它让人有点困惑的地方。网上有很多资源,而且都有很大的不同。我需要创建一个类来保存数据和{ get; set; }
吗?
RESTsharp或Json.NET会让我的工作更轻松吗?欢迎提出任何建议。
您不需要任何第三方JSON库。
-
将数据转换为字符串。你已经做到了。
-
创建数据类。我喜欢igrali使用Visual Studio来实现这一点的想法。但如果数据很简单,只需自己编写类即可:
[DataContract] public class PersonInfo { [DataMember] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } }
-
从字符串反序列化到类:
我喜欢使用这个通用助手:
public static T Deserialize<T>(string json)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(stream);
return obj;
}
}
然后这样称呼它:
PersonInfo info = (PersonInfo)JsonHelper.Deserialize<PersonInfo>(s);
首先,您需要创建表示您收到的JSON模型的类。有不止一种方法可以做到这一点-您可以使用json2csharp,甚至更好的方法是Visual Studio的功能,名为将JSON粘贴为类(可以在以下位置找到:编辑->特殊粘贴->将JSON粘贴成类)。
一旦您有了这些类,就可以使用Json.NET来帮助您处理Json响应。您可能想要将接收到的字符串(JSON)反序列化为C#对象。为此,您只需调用JsonConvert.DeserializeObject
方法即可。
var myObject = JsonConvert.DeserializeObject<MyClass>(json);
其中MyClass
是要反序列化为的任何类型。
有一个WebApi客户端将为您处理所有序列化。
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
这是一个示例:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}'t${1}'t{2}", product.Name, product.Price, product.Category);
}
}
async Task Main()
{
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage())
{
request.RequestUri = new Uri("http://www.trola.si/bavarski");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = HttpMethod.Get;
var result = await client.SendAsync(request);
string jsonStr = await result.Content.ReadAsStringAsync();
Result obj = JsonConvert.DeserializeObject<Result>(jsonStr);
obj.Dump();
}
}
}
// Define other methods and classes here
public class Result
{
[JsonProperty(PropertyName = "stations")]
public Station[] Stations { get; set;}
}
public class Station
{
[JsonProperty(PropertyName = "number")]
public string Number { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "buses")]
public Bus[] Buses { get; set; }
}
public class Bus
{
[JsonProperty(PropertyName = "direction")]
public string Direction { get; set; }
[JsonProperty(PropertyName = "number")]
public string Number { get; set; }
[JsonProperty(PropertyName = "arrivals")]
public int[] Arrivals { get; set; }
}