基于动态项列表创建类实例

时间:2016-03-03 20:39:24

标签: c# json visual-studio list visual-studio-2015

我不确定我是否可以通过为我正在运行的流程创建一个单独的类来使我的代码更清晰,但我这样做是因为它是我如何知道的这样做。

我的主要目标是根据通过HtmlAgilityPack收集的数据创建一个JSON文件。我在过去几天一直在处理这个问题,但我设法找到了办法。我设法创建了一个JSON文件,其中包含检索到的信息,但它并没有将信息分成对象数组中的单独对象。相反,它将所有数据聚集为1个对象。

这种情况正在发生,因为我从未在字符串列表中使用已解析的html数据创建对象。我需要创建一个由解析的html数据制作的对象列表,并将它们添加到列表中,而不是创建单独的列表并将它们组合在一起。

为了测试这个假设方法,我创建了3个类实例并给它们值,以查看JSON文件是否创建了所需的对象数组。测试时,它根据需要创建了JSON对象数组。

JSON创建:

[{"FavsGTS":"GT1","FavsGPICS":"GP1","FavsRNS":"RN1","FavsPIS":"PI1","FavsIsOns":"true"},
{"FavsGTS":"GT2","FavsGPICS":"GP2","FavsRNS":"RN2","FavsPIS":"PI2","FavsIsOns":"false"},
{"FavsGTS":"GT3","FavsGPICS":"GP3","FavsRNS":"RN3","FavsPIS":"PI3","FavsIsOns":"true"}]

现在我试图弄清楚如何根据收集的html数据动态创建实例。

我想到的是做了类似的事情:

gamertagsFav = new List<string>(FavsGTS.Count);
            gamertagsFav.AddRange(FavsGTS);

            foreach(string gamertagfav in gamertagsFav)
            {
                //creates a class instance and adds the parsed data in the same order.   
            }

生成的实例的一个例子是休闲:

gamerprofileFav gpfav1 = new gamerprofileFav()
            {
                FavsGTS = "gt1",
                FavsGPICS = "gpic1",
                FavsRNS = "rn1",
                FavsPIS = "pi1",
                FavsIsOns = "ison1"
            };

这是可能的,因为所有解析的数据都是相同的顺序。

我的代码有点乱,但它就像休耕一样:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.IO;

namespace Parser_Test_1._0
{
    public partial class Form1 : Form
    {
        public List<string> FavsGTS { get; private set; }
        public List<string> FavsGPICS { get; private set; }
        public List<string> FavsRNS { get; private set; }
        public List<string> FavsPIS { get; private set; }
        public List<string> FavsIsOns { get; private set; }
        public List<string> allPlayers { get; private set; }
        public List<string> gamertagsFav { get; private set; }

        public Form1()
        {
            InitializeComponent();
        }

        public class gamerprofileFav
        {
            public string FavsGTS { get; set; }
            public string FavsGPICS { get; set; }
            public string FavsRNS { get; set; }
            public string FavsPIS { get; set; }
            public string FavsIsOns { get; set; }

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(@"C:\Users\josec\Documents\Visual Studio 2015\Projects\THE XBOX PROJECT\Parser-Test-1.0\Parser-Test-1.0\bin\Debug\xbFrSourceCode.txt");

            string datacollected1 = doc.DocumentNode.SelectNodes("//*[@id=\"favoritesContent\"]/div[2]/div[2]/ul")[0].InnerHtml;
            string datacollected2 = doc.DocumentNode.SelectNodes("//*[@id=\"friendsContent\"]/div[2]/div[2]")[0].InnerHtml;
            label1.Text = datacollected1;
            label2.Text = datacollected2;

            //StreamWriter sw = new StreamWriter("datacollected1.txt");
            //sw.Write(datacollected1);
            //sw.Close();

            //Gamertags
            HtmlAgilityPack.HtmlDocument favs = new HtmlAgilityPack.HtmlDocument();
            favs.LoadHtml(datacollected1);

            FavsGTS = new List<string>();
            HtmlNodeCollection gts = favs.DocumentNode.SelectNodes("//li[@data-gamertag]");
            foreach (var gt in gts)
            {
                string datagamertag = gt.Attributes["data-gamertag"].Value;
                FavsGTS.Add(datagamertag);
            }

            listBox1.DataSource = FavsGTS;

            FavsGPICS = new List<string>();
            HtmlNodeCollection gpics = favs.DocumentNode.SelectNodes("//li/a[1]/img[1][@src]");
            foreach (var gpic in gpics)
            {
                string datagpic= gpic.Attributes["src"].Value;
                FavsGPICS.Add(datagpic);
            }

            listBox2.DataSource = FavsGPICS;

            FavsRNS = new List<string>();
            HtmlNodeCollection rns = favs.DocumentNode.SelectNodes("//li/div[2]/div[2]/div[1]/div[1]");
            foreach (var rn in rns)
            {
                string datarn = rn.InnerText;
                FavsRNS.Add(datarn);
            }

            listBox3.DataSource = FavsRNS;

            FavsPIS = new List<string>();
            HtmlNodeCollection pis = favs.DocumentNode.SelectNodes("//li/div[2]/div[2]/div[1]/div[2]");
            foreach (var pi in pis)
            {
                string datapi = pi.InnerText;
                FavsPIS.Add(datapi);
            }

            listBox4.DataSource = FavsPIS;

            FavsIsOns = new List<string>();
            HtmlNodeCollection isons = favs.DocumentNode.SelectNodes("//li[@data-isonline]");
            foreach (var ison in isons)
            {
                string dataison = ison.Attributes["data-isonline"].Value;
                FavsIsOns.Add(dataison);
            }

            listBox5.DataSource = FavsIsOns;
            //Test
            gamertagsFav = new List<string>(FavsGTS.Count);
            gamertagsFav.AddRange(FavsGTS);

            foreach(string gamertagfav in gamertagsFav)
            {

            }



            //Merge
            allPlayers = new List<string>(FavsGTS.Count + FavsGPICS.Count + FavsRNS.Count + FavsPIS.Count + FavsIsOns.Count);
            allPlayers.AddRange(FavsGTS);
            allPlayers.AddRange(FavsGPICS);
            allPlayers.AddRange(FavsRNS);
            allPlayers.AddRange(FavsPIS);
            allPlayers.AddRange(FavsIsOns);

            //GpsFav //+Start+
            gamerprofileFav gpfav1 = new gamerprofileFav()
            {
                FavsGTS = "GT1",
                FavsGPICS = "GP1",
                FavsRNS = "RN1",
                FavsPIS = "PI1",
                FavsIsOns = "true"
            };
            gamerprofileFav gpfav2 = new gamerprofileFav()
            {
                FavsGTS = "GT2",
                FavsGPICS = "GP2",
                FavsRNS = "RN2",
                FavsPIS = "PI2",
                FavsIsOns = "false"
            };
            gamerprofileFav gpfav3 = new gamerprofileFav()
            {
                FavsGTS = "GT3",
                FavsGPICS = "GP3",
                FavsRNS = "RN3",
                FavsPIS = "PI3",
                FavsIsOns = "true"
            };

            List<gamerprofileFav> gpfavs = new List<gamerprofileFav>();
            gpfavs.Add(gpfav1);
            gpfavs.Add(gpfav2);
            gpfavs.Add(gpfav3);
            //GgsFav //-END-

            listBox6.DataSource = allPlayers;
            listBox7.DataSource = gamertagsFav;

            //JSON Serialize
            //string data = JsonConvert.SerializeObject(gpfavs);
            //File.WriteAllText("data.json", data);
        }
        public class gpsFav
        {



        }

    }
}

运行时这是Form1: enter image description here

5个小列表中显示的数据是我希望按照它们出现的相同顺序分配给生成的实例的数据。这样我就可以基于这些生成的实例创建一个列表,我可以将其序列化为JSON文件。

1 个答案:

答案 0 :(得分:0)

为了避免做所有艰苦的工作,已经有一个选项可以将JSON对象反序列化为可以使用的.NET对象,这是一段代码示例;

public class RootObject
{
    public string FavsGTS { get; set; }
    public string FavsGPICS { get; set; }
    public string FavsRNS { get; set; }
    public string FavsPIS { get; set; }
    public string FavsIsOns { get; set; }
}

虽然您只需按顺序反序列化它;

RootObject gamertag_sample = JsonConvert.DeserializeObject<RootObject>(jsonstr);

当然,如果你传递一个RootObject数组,你需要用<RootObject>替换<RootObject[]>,依此类推。

据我所知,这是您寻求解决方案的唯一问题,或者我错过了什么?

编辑: 使用动态对象,您可以创建任何您想要的值条目,但是在此之前您需要完成一系列任务。

// this would contain your key,value for the generated instance.
// {example_key, "value"} would result later in myObject.example_key (returning "value")
var expandoObj = new ExpandoObject();
var eoCollection = (ICollection<KeyValuePair<string, object>>)expandoObj;
// add your key value pairs here
eoCollection.Add(new KeyValuePair<string, object>("example", "example value"));

dynamic myDynamicObject = expandoObj;
// myDynamicObject.example will return "example value", and would result in json:
//    "example":"example value"