'Unable to convert a JSON file to a ListView
I'm unable to convert a JSON file (opened with OpenFileDialog) to a ListView.
My JSON file looks something like this:
{
"m_Version": 9,
"DisplayName": "#STR_EXPANSION_MARKET_CATEGORY_AMMO",
"Icon": "Deliver",
"Color": "FBFCFEFF",
"InitStockPercent": 75.0,
"Items": [
{
"ClassName": "ammo_12gapellets",
"MaxPriceThreshold": 10,
"MinPriceThreshold": 5,
"SellPricePercent": -1,
"MaxStockThreshold": 500,
"MinStockThreshold": 1,
"QuantityPercent": -1,
"SpawnAttachments": [],
"Variants": []
},
{
"ClassName": "ammo_12garubberslug",
"MaxPriceThreshold": 8,
"MinPriceThreshold": 4,
"SellPricePercent": -1,
"MaxStockThreshold": 500,
"MinStockThreshold": 1,
"QuantityPercent": -1,
"SpawnAttachments": [],
"Variants": []
}
]
}
Opening the file and trying to add:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JSON Files (*.json)|*.json|All files (*.*)|*.*";
ofd.Multiselect = false;
if(ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
var fileStream = ofd.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
var content = reader.ReadToEnd();
var result = JsonConvert.DeserializeObject<Item>(content);
listView1.Items.Add(new ListViewItem(new string[] { result.ClassName}));
}
}
}
public partial class Items
{
public Item[] Item { get; set; }
}
public partial class Item
{
[JsonProperty("ClassName")]
public string ClassName { get; set; }
}
When I load the file, it adds something to the first column, however it is just an empty string. How can I get all "Items" to my ListView?
Solution 1:[1]
try this
var content = reader.ReadToEnd();
JArray items= (JArray) JObject.Parse(content)["Items"];
foreach (var item in items)
{
var namesList= item.Properties().Select(i => i.Value.ToString()).ToArray();
listView1.Items.Add(new ListViewItem(namesList));
}
but IMHO it is better to create DataTable from Json and use it a list view source
var content = reader.ReadToEnd();
DataTable items= JObject.Parse(content)["Items"].ToObject<DataTable>();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
