Serializing "string list" to JSON in C# -
(i'v restated question here: creating class instances based on dynamic item lists)
i'm working on program in visual studio 2015 c#.
i have 5 list strings contain data wish serialize json file.
public list<string> name { get; private set; } public list<string> userimageurl { get; private set; } public list<string> nickname { get; private set; } public list<string> info { get; private set; } public list<string> available { get; private set; }
an example of desired json file format fallowing:
{ "users" : [ { "name" : "name1", "userimageurl" : "userimageurl1", "nickname" : "nickname1", "info" : "info1", "available" : false, }, { "name" : "name2", "userimageurl" : "userimageurl2", "nickname" : "nickname2", "info" : "info2", "available" : false, }, { "name" : "name3", "userimageurl" : "userimageurl3", "nickname" : "nickname3", "info" : "info3", "available" : false, }, { "name" : "name4", "userimageurl" : "userimageurl4", "nickname" : "nickname4", "info" : "info4", "available" : false, } ] }
note there might errors in json example above.
i've tried combining 5 lists create 1 list serialize using following code:
users = new list<string>(name.count + userimageurl.count + nickname.count + info.count + available.count); allplayers.addrange(name); allplayers.addrange(userimageurl); allplayers.addrange(nickname); allplayers.addrange(info); allplayers.addrange(available);
then serialize list fallowing code:
string data = jsonconvert.serializeobject(users); file.writealltext("data.json", data);
this creates array of unorganized objects. wish know how can organize them expressed in format above.
ps: i'm pretty new coding can tell. sorry if i'm not expressing question correctly or using right terminology. also, not original code. code creates lists wish serialize json file.
pss: data collected using htmlagilitypack. asked question yesterday asking how parse html file , serialize it's data json file. using htmlagilitypack specific data in c# , serialize json . nobody answered, decided try , myself. method used may not best, knowledge have.
i suggest refactoring code start - instead of having 5 "parallel collections", have single collection of new type, user
:
public class user { public string name { get; set; } public string imageurl { get; set; } public string nickname { get; set; } public string info { get; set; } public bool available { get; set; } } ... // in containing type public list<user> users { get; set; }
this make life simpler not json, rest of code - because no longer have possibility of having more nicknames image urls, etc. in general, having multiple collections must kept in sync each other antipattern. there are times it's appropriate - typically providing different efficient ways of retrieving same data - it's best avoided.
Comments
Post a Comment