根据动态项目列表创建类实例 [英] Creating class instances based on dynamic item lists
问题描述
我不确定是否可以通过为正在运行的进程创建一个单独的类来使代码更整洁,但是我这样做是因为我知道如何做到这一点.
I'm not sure if I could make my code cleaner by creating a separate class for the process I'm running but I'm doing it this way because it's how I know to do it.
我的主要目标是根据通过HtmlAgilityPack收集的数据创建JSON文件.最近几天,我一直在处理此问题,但设法找到了解决方法.我设法用检索到的信息创建了一个JSON文件,但是它没有将信息分成对象数组中的单独对象.而是将所有数据聚集为1个对象.
My main objective is to create a JSON file from data collected through HtmlAgilityPack. I've been working with this problem the last couple days but I managed to figure out a way to do it. I managed to create a JSON file with the information retrieved but it didn't divide the information into separate objects in an object array. Instead it clustered up all the data as 1 object.
之所以发生这种情况,是因为我从未在字符串列表中使用已解析的html数据创建对象.除了创建单独的列表并将其组合之外,我需要创建一个由解析的html数据制成的对象的列表,并将它们添加到列表中.
This was happening because I never created the objects with the parsed html data in the string list. Instead of creating separate lists and combining them, I need to create a list of objects made from the parsed html data and add them to a list.
为了测试这种假设的方法,我创建了3个类实例,并为它们提供了值,以查看JSON文件是否创建了所需的对象数组.经过测试,它会根据需要创建对象的JSON数组.
To test out this hypothetical method I created 3 class instances and gave them values to see if the JSON file created the desired array of objects. When tested, it created the JSON array of objects as desired.
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数据动态创建实例.
Now I'm trying to figure out how can I dynamically create instances based out of the collected html data.
我想到的是在做类似的事情:
What I had in mind was doing something like:
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.
}
生成的实例的一个例子是休假:
An example of a generated instance would be as fallows:
gamerprofileFav gpfav1 = new gamerprofileFav()
{
FavsGTS = "gt1",
FavsGPICS = "gpic1",
FavsRNS = "rn1",
FavsPIS = "pi1",
FavsIsOns = "ison1"
};
之所以可行,是因为所有解析的数据都具有相同的顺序.
This is possible because all the parsed data is in the same order.
我的代码有点混乱,但是却很有趣:
My code is a bit messy, but it is as fallows:
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:
This is the Form1 when run:
5个小列表中显示的数据是我希望按照出现的顺序分配给生成的实例的数据.这样,我可以根据这些生成的实例创建一个列表,然后将其序列化为JSON文件.
The data presented in the 5 small lists is the data that I wish to assign to the generated instances in the same order they appear. That way I can create a list based out of these generated instances which I can serialize to a JSON file.
推荐答案
为避免进行所有艰苦的工作,已经有一个选项可以将JSON对象反序列化为可以使用的.NET对象,例如您的一段代码;
To avoid doing all of the hard work, there is already an option to deserialize a JSON object into a .NET object that you can work with, an example with your piece of code;
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; }
}
您只是反序列化方式;
While you simply deserialize it by;
RootObject gamertag_sample = JsonConvert.DeserializeObject<RootObject>(jsonstr);
当然,如果将RootObject数组传递给它,则需要用<RootObject[]>
替换<RootObject>
,依此类推.
Of course if you pass it an array of RootObject, you'll need to replace <RootObject>
with <RootObject[]>
and so on with the type.
据我了解,这是您寻求解决方案的唯一问题,或者我错过了什么?
As far as I understood this was the only problem you were seeking for a solution or have I missed something?
使用动态对象,您可以创建所需的任何值条目,但是您需要先完成一系列任务.
With dynamic object you can create any value entry you wish, you'll need to go through a series of tasks to do so before however.
// 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"
这篇关于根据动态项目列表创建类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!