Reputation: 35
I've done my research and I've found several solutions to problems that are almost the same as mine but none of them have worked so far. What I'm trying to accomplish is to read a json file where the first item is an array, like this:
{
"the_array":[
The error I get is: Object reference not set to an instance of an object.
The closest I've gotten is when I try to write out the entire json but then I only get the first item in the array. [edit: clarification below]
Here's the code:
using Newtonsoft.Json;
using System;
using System.IO;
namespace JsonToXML
{
class Program
{
static void Main(string[] args)
{
try
{
string json = File.ReadAllText(@"w:\code\csharp\JsonToXML\simple-sample.json").ToString();
Accounts accs = JsonConvert.DeserializeObject<Accounts>(json);
foreach (var acc in accs.account_list)
{
Console.Write(acc.id.ToString());
Console.ReadKey(true);
}
catch(Exception ex)
{
Console.Write(ex.Message.ToString());
Console.ReadKey(true);
}
}
}
}
using System.Collections.Generic;
namespace JsonToXML
{
class Accounts
{
public List<accounts> account_list { get; set; }
public class accounts
{
public string id { get; set; }
public string bic { get; set; }
}
}
}
{
"account_list": [
{
"id": "AsdF01234EfgH4567",
"bic": "A"
},
{
"id": "AbcD1234eFgH568",
"bic": "B"
},
{
"id": "Baas786DD5886RT",
"bic": "C"
},
{
"id": "458A889B8889T784W",
"bic": "D"
}
]
}
I've also tried using List<Accounts>
with no success.
If anything about the question is unclear, just let me know and I'll clarify as best I can.
I'm coding this in .Net Core
[edit: clarification from above] If I try:
var accs = JsonConvert.DeserializeObject<dynamic>(json);
Console.Write(accs.ToString());
The result is: { "id": "AsdF01234EfgH4567", "bic": "SWEDSESS" }
The problem was within the json file. While it looked like it worked, somehow sublime had saved it incorrectly. After remaking the json file with the exact same content, it worked as intended.
Upvotes: 0
Views: 1608
Reputation: 5281
Its simple you only GET FIRST because this `
Console.ReadKey(true)`
Readkey is used to wait for user key press so it wont execute further until you press some key read Here
Final Code
try
{
string json = File.ReadAllText(@"w:\code\csharp\JsonToXML\simple-sample.json").ToString();
Accounts accs = JsonConvert.DeserializeObject<Accounts>(json);
foreach (var acc in accs.account_list)
{
Console.WriteLine(acc.id.ToString());
}
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
throw ex;
}
Console.ReadKey();
}
Upvotes: 1