C# 在c语言中反序列化JSON数据的好方法,但很简单#

C# 在c语言中反序列化JSON数据的好方法,但很简单#,c#,json,visual-studio,rest,uwp,C#,Json,Visual Studio,Rest,Uwp,我已经挣扎了很长一段时间,但现在我成功地从web API中提取JSON数据 到目前为止我的代码(到目前为止只有一个测试片段): 就拉取数据而言,这还可以,对吗 这里有点让人困惑。网上有很多资源,它们都有很大的不同。我是否需要创建一个包含数据和{get;set;}的类 RESTsharp或Json.NET会让我的工作更轻松吗?如有任何建议,我们将不胜感激 有一个WebApi客户端,它将为您处理所有序列化 以下是一个示例: using (var client = new HttpClient())

我已经挣扎了很长一段时间,但现在我成功地从web API中提取JSON数据

到目前为止我的代码(到目前为止只有一个测试片段):

就拉取数据而言,这还可以,对吗

这里有点让人困惑。网上有很多资源,它们都有很大的不同。我是否需要创建一个包含数据和
{get;set;}
的类


RESTsharp或Json.NET会让我的工作更轻松吗?如有任何建议,我们将不胜感激

有一个WebApi客户端,它将为您处理所有序列化

以下是一个示例:

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);
    }
}
使用(var-client=new-HttpClient())
{
client.BaseAddress=新Uri(“http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
//新代码:
httpresponsemessageresponse=wait client.GetAsync(“api/products/1”);
if(响应。IsSuccessStatusCode)
{
Product=wait response.Content.ReadAsAsync();
Console.WriteLine(“{0}\t${1}\t{2}”,product.Name,product.Price,product.Category);
}
}

有一个WebApi客户端,它将为您处理所有序列化

以下是一个示例:

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);
    }
}
使用(var-client=new-HttpClient())
{
client.BaseAddress=新Uri(“http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
//新代码:
httpresponsemessageresponse=wait client.GetAsync(“api/products/1”);
if(响应。IsSuccessStatusCode)
{
Product=wait response.Content.ReadAsAsync();
Console.WriteLine(“{0}\t${1}\t{2}”,product.Name,product.Price,product.Category);
}
}

首先,您需要创建表示您收到的JSON模型的类。实现这一点的方法不止一种——您可以使用Visual Studio的功能,该功能名为将JSON粘贴为类(可以在以下位置找到:编辑->粘贴特殊->将JSON粘贴为类)

一旦有了这些类,就可以使用Json.NET来帮助您处理Json响应。您可能希望将接收到的字符串(JSON)反序列化为C#对象。为此,只需调用
JsonConvert.DeserializeObject
方法即可

var myObject = JsonConvert.DeserializeObject<MyClass>(json);
var myObject=JsonConvert.DeserializeObject(json);

其中,
MyClass
是您要反序列化到的任何类型。

首先,您需要创建表示您收到的JSON模型的类。实现这一点的方法不止一种——您可以使用Visual Studio的功能,该功能名为将JSON粘贴为类(可以在以下位置找到:编辑->粘贴特殊->将JSON粘贴为类)

一旦有了这些类,就可以使用Json.NET来帮助您处理Json响应。您可能希望将接收到的字符串(JSON)反序列化为C#对象。为此,只需调用
JsonConvert.DeserializeObject
方法即可

var myObject = JsonConvert.DeserializeObject<MyClass>(json);
var myObject=JsonConvert.DeserializeObject(json);

其中,
MyClass
是您要反序列化到的任何类型。

您不需要任何第三方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;
            }
         }
    
    publicstatict反序列化(字符串json)
    {
    使用(MemoryStream stream=new MemoryStream(Encoding.UTF8.GetBytes(json)))
    {
    DataContractJsonSerializer serializer=新的DataContractJsonSerializer(typeof(T));
    T obj=(T)serializer.ReadObject(流);
    返回obj;
    }
    }
    
    然后这样称呼它:

                PersonInfo info = (PersonInfo)JsonHelper.Deserialize<PersonInfo>(s);
    
    PersonInfo info=(PersonInfo)JsonHelper;
    
    您不需要任何第三方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;
            }
         }
    
    publicstatict反序列化(字符串json)
    {
    使用(MemoryStream stream=new MemoryStream(Encoding.UTF8.GetBytes(json)))
    {
    DataContractJsonSerializer serializer=新的DataContractJsonSerializer(typeof(T));
    T obj=(T)serializer.ReadObject(流);
    返回obj;
    }
    }
    
    然后这样称呼它:

                PersonInfo info = (PersonInfo)JsonHelper.Deserialize<PersonInfo>(s);
    
    PersonInfo info=(PersonInfo)JsonHelper;
    
    Json.net在这方面帮助很大。您可以反序列化为匿名类型或POCO对象。我希望下面的解决方案能帮助您开始

    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; }
    }
    
    async Task Main()
    {
    使用(var client=new HttpClient())
    {
    使用(var request=new HttpRequestMessage())
    {
    request.RequestUri=新Uri(“http://www.trola.si/bavarski");
    request.Headers.Accept.Add(新的MediaTypeWithQualityHeaderValue(“application/json”);
    request.Method=HttpMethod.Get;
    var result=wait client.sendaync(请求);
    字符串jsonStr=await result.Content.ReadAsStringAsync();
    结果obj=JsonConvert.DeserializeObject(jsonStr);
    obj.Dump();
    }
    }
    }
    //在此处定义其他方法和类
    公开课成绩
    {
    [JsonProperty(PropertyName=“stations”)]
    公共电台[]台{get;set;}
    }
    公营电台
    {
    [JsonProperty(PropertyName=“number”)]
    公共字符串号{ge