试图反序列化一个json文件C# [英] Trying to deserialize a json file C#

查看:79
本文介绍了试图反序列化一个json文件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,伙计们。我第一次问这里。所以,我有一种情况试图从Json文件中获取一些信息。我希望获得Public Class Valore和Resultados内部的信息。这就是我的代码的样子:

Hello, guys. My first time asking here. So, I got a situation trying to get some information from a Json File. I want to reach the information that is inside of the Public Class Valore and Resultados. This is how my code looks like:

public class Valore
        public string fecha { get; set; }
    {
    public string hora { get; set; }
    public string pml { get; set; }
    public string pml_ene { get; set; }
    public string pml_per { get; set; }
    public string pml_cng { get; set; }
}

public class Resultado
{
    public string clv_nodo { get; set; }
    public List<valore> Valores { get; set; }
}

public class RootObject
{
    public string nombre { get; set; }
    public string proceso { get; set; }
    public string sistema { get; set; }
    public string area { get; set; }
    public List<resultado> Resultados { get; set; }
    public string status { get; set; }
}



class Program
{
    static void Main(string[] args)
    {
        RootObject PrecioMarginal;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"Someplaceoninternet");
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            string json = reader.ReadToEnd();
            price = JsonConvert.DeserializeObject<rootobject>(json);
           
        }
        Console.WriteLine("El estatus del nodo es: " + Price.status);
        Console.ReadKey();
    }
}





我的尝试:



不是太多,我第一次使用C#编写代码



What I have tried:

Not too much, my first time making code with C#

推荐答案

这个问题在这里有很多问题,所以我发表了一篇文章,回答了你的问题和其他问题:在C#中使用JSON& VB [ ^ ]
This question gets asked a lot in here, so I published an article that answers yours and other questions: Working with JSON in C# & VB[^]


我强烈建议使用Newtonsoft.JSON进行反序列化:

I can strongly recommend using Newtonsoft.JSON for deserialization:
/// <summary>
/// Load all known sheets
/// </summary>
/// <param name="path">
/// Full path to the JSON file containing the sheet data.
/// If not provided, the default will be used.</param>
/// <returns></returns>
public static List<AveryLabelSheet> Load(string path = null)
    {
    if (path == null) path = GetSensiblePathToSheetDataFile();
    if (!File.Exists(path)) throw new FileNotFoundException("Cannot locate the Sheet Data file:\n   \"" + path + "\"\nPlease check the path and try again.");
    try
        {
        all = JsonConvert.DeserializeObject<List<AveryLabelSheet>>(File.ReadAllText(path));
        }
    catch (Exception ex)
        {
        throw new FileLoadException("Unable to load Sheet Data.\nThe file \"" + path + "\" does not load correctly.", ex);
        }
    isLoaded = true;
    return new List<AveryLabelSheet>(all);
    }

一行代码完成整个工作:

One line of code does the whole job:

all = JsonConvert.DeserializeObject<List<AveryLabelSheet>>



您需要安装Newtonsoft.JSON:您可以通过NuGet包管理器将其添加到您的项目中(工具... NuGet包管理器...包管理器控制台):


You will need to install Newtonsoft.JSON: you can add it to your project via the NuGet Package Manager (Tools ... NuGet Package Manager ... Package Manager Console):

PM> Install-Package Newtonsoft.Json



顺便说一下,我第一次使用JSON数据和最近的prioject,并且使用Newtonsoft的东西非常容易:序列化并在每行代码中反序列化一个自定义类的完整列表!我发现的唯一麻烦是它只有在相关的类属性同时具有公共getter和setter时才有效 - 我最初使用私有setter,数据无法回读,这是可以理解的。


As an aside, I'm using JSON data for the first time with a recent prioject, and it's remarkably easy with the Newtonsoft stuff: serialize and deserialize a whole list of a custom class in one line of code each! The only hassle I found was it only works if the relevant class properties have both public getter and setter - I originally used private setters, and the data failed to read back, understandably.


这篇关于试图反序列化一个json文件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆