Manage your ASL charts, play aids and other documents.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
asl-charts/src/JsonConfig.cs

91 lines
2.6 KiB

using System ;
using System.IO ;
using Newtonsoft.Json ;
using Newtonsoft.Json.Linq ;
using log4net ;
// --------------------------------------------------------------------
public class JsonConfig
{
private string mFilename ;
private dynamic mData ;
public JsonConfig( string caption, string fname )
{
// initialize
ILog logger = LogManager.GetLogger( "startup" ) ;
mFilename = fname ;
// load the JSON config
string data ;
if ( File.Exists( fname ) ) {
logger.Info( $"Loading {caption}: {Path.GetFullPath(fname)}" ) ;
data = File.ReadAllText( fname ) ;
} else
data ="{}" ;
mData = JsonConvert.DeserializeObject( data ) ;
logger.Debug( mData.ToString() ) ;
}
public JsonConfig( dynamic data )
{
// initialize
mData = (data != null) ? data : new JObject() ;
}
public string getStringVal( string[] keys, string defaultVal="" )
{
// get the specified value
JToken curr = mData ;
foreach( string key in keys ) {
curr = curr[ key ] ;
if ( curr == null )
return defaultVal ;
}
return (string) curr ;
}
public void setStringVal( string[] keys, string val, bool save=true ) { setVal( keys, val, save ) ; }
public int getIntVal( string[] keys, int defaultVal=0 )
{
// get the specified value
string val = getStringVal( keys ) ;
try {
return Int32.Parse( val ) ;
} catch( FormatException ) {
return defaultVal ;
}
}
public void setIntVal( string[] keys, int val, bool save=true ) { setVal( keys, val, save ) ; }
public double getDoubleVal( string[] keys, double defaultVal=0 )
{
// get the specified value
string val = getStringVal( keys ) ;
try {
return double.Parse( val ) ;
} catch( FormatException ) {
return defaultVal ;
}
}
private void setVal( string[] keys, dynamic val, bool save )
{
// set the specified value
JToken curr = mData ;
for ( int i=0 ; i < keys.Length-1 ; ++i ) {
if ( curr[ keys[i] ] == null )
curr[ keys[i] ] = (JToken) JsonConvert.DeserializeObject( "{}" ) ;
curr = curr[ keys[i] ] ;
}
curr[ keys[keys.Length-1] ] = val ;
// save the updated config
if ( save )
File.WriteAllText( mFilename, data.ToString() ) ;
}
public dynamic data { get { return mData ; } }
}