Reputation: 860
I'm trying to capture the names and values of all nodes coming from a random Json file that I don't know its structure (uploaded by the user).
I can loop through a json string and get the info I need but how do I start from a file? If I want to deserialize it I believe I need a class to hold that data (and I don't know the file structure).
Here's how I loop through elements from a json string:
string json = @"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null)
{
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
}
else
{
Console.WriteLine("Token: {0}", reader.TokenType);
}
}
How do I read from a file and set it as a string that can be handled by the code above? It sounds like a basic question but I'm still struggling with this after several hours. All I've seen expects that you know the structure of the Json file and I don't in this case.
Upvotes: 2
Views: 13319
Reputation: 50201
This is the exact use case that dynamic
and ExpandoObject
were made for! Here you can deserialize the JSON to an object, then traverse the object's properties (look up online how to work with ExpandoObjects).
var expandoConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expandoConverter);
Or, if you were just looking to read the json from disk as a string, then use string json = File.ReadAllText(filePathAndName)
;
The above code snippet requires installing the package NewtonSoft.
Upvotes: 4
Reputation: 5951
Eriks answer was great to mention the ExpandoObject
, dynamic
and File
call. It got my +1.
I'm adding to ErikEs answer to include the package and include details required for a minimal running program.
This code was in my Program.cs
file for a Console App project type in Visual Studio 2017. You should also run install-package newtonsoft.json
in the Package Manager Console. This command will load newtonsoft.json.11.0.1
pakcage. .Net Framework was 4.6.1.
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Dynamic;
using System.IO;
namespace ReadJson
{
class Program
{
static void Main(string[] args)
{
string filePath = "<full path to json file>";
string json = File.ReadAllText(filePath);
var expandoConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expandoConverter);
//do more with your dynamic object here...
}
}
}
Upvotes: 0