Dev 1
Dev 1
Dev 1
Cinchoo
Rate this:
5.00 (1 vote)
8 Jun 2020
CPOL
Simple JSON writer for .NET
ChoETL is an open source ETL (extract, transform and load) framework for .NET. It
is a code based library for extracting data from multiple sources, transforming,
and loading into your very own data warehouse in .NET environment. You can have
data in your data warehouse in no time.
Download source code
Download binary (.NET Framework)
Download binary (.NET Standard / .NET Core)
Contents
1. Introduction
2. Requirement
3. "Hello World!" Sample
3.1. Quick write - Data First Approach
3.2. Code First Approach
3.3. Configuration First Approach
4. Writing All Records
5. Write Records Manually
6. Customize JSON Record
8. Customize JSON Fields
8.1. DefaultValue
8.2. ChoFallbackValue
8.3. Type Converters
8.3.1. Declarative Approach
8.3.2. Configuration Approach
8.3.3. Custom Value Converter Approach
8.4. Validations
8.5. ChoIgnoreMember
8.6. StringLength
8.6. Display
8.7. DisplayName
10. Callback Mechanism
10.1 Using JSONWriter events
10.2 Implementing IChoNotifyRecordWrite interface
10.1 BeginWrite
10.2 EndWrite
10.3 BeforeRecordWrite
10.4 AfterRecordWrite
10.5 RecordWriteError
10.6 BeforeRecordFieldWrite
10.7 AfterRecordFieldWrite
10.8 RecordWriteFieldError
11. Customization
12. Using Dynamic Object
13. Exceptions
15. Using MetadataType Annotation
16. Configuration Choices
16.1 Manual Configuration
16.2 Auto Map Configuration
16.3 Attaching MetadataType class
17. ToTextAll Helper Method
17a. ToText Helper Method
18. Writing DataReader Helper Method
19. Writing DataTable Helper Method
20. Advanced Topics
20.1 Override Converters Format Specs
20.2 Currency Support
20.3 Enum Support
20.4 Boolean Support
20.5 DateTime Support
21. Fluent API
21.1. NullValueHandling
21.2. Formatting
21.3 WithFields
21.4 WithField
21.5. IgnoreFieldValueMode
21.6 ColumnCountStrict
21.7. Configure
21.8. Setup
1. Introduction
ChoETL is an open source ETL (extract, transform and load) framework for .NET. It
is a code based library for extracting data from multiple sources, transforming,
and loading into your very own data warehouse in .NET environment. You can have
data in your data warehouse in no time.
This article talks about using ChoJSONWriter component offered by ChoETL framework.
It is a simple utility class to save JSON data to a file / external data source.
Features:
Follows JSON standard file rules.
Supports culture specific date, currency and number formats while generating files.
Supports different character encoding.
Provides fine control of date, currency, enum, boolean, number formats when writing
files.
Detailed and robust error handling, allowing you to quickly find and fix problems.
Shorten your development time.
2. Requirement
This framework library is written in C# using .NET 4.5 Framework / .NET core 2.x.
This is the combined approach to define POCO entity class along with attaching JSON
configuration parameters declaratively. id is required column and name is optional
value column with default value "XXXX". If name is not present, it will take the
default value.
[ChoJSONRecordField]
[DefaultValue("XXXX")]
public string Name
{
get;
set;
}
writer.Write(rec2);
6. Customize JSON Record
Using ChoJSONRecordObjectAttribute, you can customize the POCO entity object
declaratively.
FieldName - JSON field name. If not specified, POCO object property name will be
used as field name.
Size - Size of JSON column value.
NullValue - Special null value text expect to be treated as null value from JSON
file at the field level.
ErrorMode - This flag indicates if an exception should be thrown if writing and an
expected field failed to convert and write. Possible values are:
IgnoreAndContinue - Ignore the error and continue to load other properties of the
record.
ReportAndContinue - Report the error to POCO entity if it is of IChoRecord type.
ThrowAndStop - Throw the error and stop the execution.
8.1. DefaultValue
Any POCO entity property can be specified with default value using
System.ComponentModel.DefaultValueAttribute. It is the value used to write when the
JSON value null (controlled via IgnoreFieldValueMode).
8.2. ChoFallbackValue
Any POCO entity property can be specified with fallback value using
ChoETL.ChoFallbackValueAttribute. It is the value used when the property is failed
to writer to JSON. Fallback value only set when ErrorMode is either
IgnoreAndContinue or ReportAndContinue.
There are couple of ways you can specify the converters for each field
Declarative Approach
Configuration Approach
8.3.1. Declarative Approach
This model is applicable to POCO entity object only. If you have POCO class, you
can specify the converters to each property to carry out necessary conversion on
them. Samples below shows the way to do it.
config.JSONRecordFieldConfigurations.Add(new
ChoJSONRecordFieldConfiguration("Name"));
config.JSONRecordFieldConfigurations.Add(new
ChoJSONRecordFieldConfiguration("Name1"));
In above, we construct and attach the IntConverter to 'Id' field using AddConverter
helper method in ChoJSONRecordFieldConfiguration object.
Likewise, if you want to remove any converter from it, you can use RemoveConverter
on ChoJSONRecordFieldConfiguration object.
[ChoJSONRecordField]
[Required]
[DefaultValue("ZZZ")]
[ChoFallbackValue("XXX")]
public string Name { get; set; }
}
In example above, used Range validation attribute for Id property. Required
validation attribute to Name property. JSONWriter performs validation on them
before saving the data to file when Configuration.ObjectValidationMode is set to
ChoObjectValidationMode.MemberLevel or ChoObjectValidationMode.ObjectLevel.
Some cases, you may want to take control and perform manual self validation within
the POCO entity class. This can be achieved by inheriting POCO object from
IChoValidatable interface.
Tip: Any exceptions raised out of these interface methods will be ignored.
Sample below shows how to use the BeforeRecordLoad callback method to skip lines
stating with '%' characters.
parser.Write(rec);
}
}
Likewise you can use other callback methods as well with JSONWriter.
[ChoJSONRecordField]
[Required]
[DefaultValue("ZZZ")]
[ChoFallbackValue("XXX")]
public string Name { get; set; }
[ChoJSONRecordField]
[Required]
[DefaultValue("ZZZ")]
[ChoFallbackValue("XXX")]
public string Name { get; set; }
[MetadataType(typeof(EmployeeRecMeta))]
public partial class EmployeeRec
{
public int Id { get; set; }
public string Name { get; set; }
}
Sample below shows how to attach Metadata class for sealed or third party POCO
class by using ChoMetadataRefTypeAttribute on it.
[ChoJSONRecordField]
[Required]
[DefaultValue("ZZZ")]
[ChoFallbackValue("XXX")]
public string Name { get; set; }
Tip: If you want to skip the record from writing, set the source to null.
Return true to continue the load process, otherwise return false to stop the
process.
Return true to continue the load process, otherwise return false to stop the
process.
Return true to continue the load process, otherwise return false to stop the
process.
Return true to continue the load process, otherwise return false to stop the
process.
Return true to continue the load process, otherwise return false to stop the
process.
[ChoJSONRecordField]
[StringLength(1)]
[DefaultValue("ZZZ")]
[ChoFallbackValue("XXX")]
public string Name { get; set; }
Manual Configuration
Auto Map Configuration
Attaching MetadataType class
I'm going to show you how to configure the below POCO entity class on each approach
First define a schema class for EmployeeRec POCO entity class as below
[ChoJSONRecordField]
public string Name { get; set; }
}
Then you can use it to auto map JSON columns by using
ChoJSONRecordConfiguration.MapRecordFields method
This model, accounts for everything by defining MetadataType class and specifying
the JSON configuration parameters declaratively. This is useful when your POCO
entity is sealed and not partial class. Also it is one of favorable and less error-
prone approach to configure JSON parsing of POCO entity.
[ChoJSONRecordField]
[StringLength(1)]
[DefaultValue("ZZZ")]
[ChoFallbackValue("XXX")]
public string Name { get; set; }
Console.WriteLine(ChoJSONWriter.ToTextAll(objs));
}
17a. ToText Helper Method
This is little nifty helper method to generate JSON formatted output from an
object. It helps you to run and play with different options to see the JSON output
quickly in test environment.
Console.WriteLine(ChoJSONWriter.ToText(rec1));
}
18. Writing DataReader Helper Method
This helper method lets you to create JSON file / stream from ADO.NET DataReader.
Console.WriteLine(json.ToString());
}
20. Advanced Topics
20.1 Override Converters Format Specs
Cinchoo ETL automatically parses and converts each JSON column values to the
corresponding JSON column's underlying data type seamlessly. Most of the basic .NET
types are handled automatically without any setup needed.
There are 2 sets of format specs members given to each intrinsic type, one for
loading and another one for writing the value, except for Boolean, Enum, DataTime
types. These types have only one member for both loading and writing operations.
Console.WriteLine(json.ToString());
}
20.2 Currency Support
Cinchoo ETL provides ChoCurrency object to read and write currency values in JSON
files. ChoCurrency is a wrapper class to hold the currency value in decimal type
along with support of serializing them in text format during JSON load.
Console.WriteLine(json.ToString());
}
Sample above shows how to output currency values using dynamic object model. As the
currency output will have thousand comma separator, this will fail to generate JSON
file. To overcome this issue, we specify the writer to quote all fields.
Sample below shows how to use ChoCurrency JSON field in POCO entity class.
Console.WriteLine(json.ToString());
}
20.3 Enum Support
Cinchoo ETL implicitly handles parsing/writing of enum column values from JSON
files. If you want to fine control the parsing of these values, you can specify
them globally via ChoTypeConverterFormatSpec.EnumFormat. Default is
ChoEnumFormatSpec.Value
Console.WriteLine(json.ToString());
}
20.4 Boolean Support
Cinchoo ETL implicitly handles parsing/writing of boolean JSON column values from
JSON files. If you want to fine control the parsing of these values, you can
specify them globally via ChoTypeConverterFormatSpec.BooleanFormat. Default value
is ChoBooleanFormatSpec.ZeroOrOne
Console.WriteLine(json.ToString());
}
20.5 DateTime Support
Cinchoo ETL implicitly handles parsing/writing of datetime JSON column values from
JSON files using system Culture or custom set culture. If you want to fine control
the parsing of these values, you can specify them globally via
ChoTypeConverterFormatSpec.DateTimeFormat. Default value is 'd'.
You can use any valid standard or custom datetime .NET format specification to
parse the datetime JSON values from the file.
Console.WriteLine(json.ToString());
}
Sample above shows how to generate custom datetime values to JSON file.
Note: As the datetime values contains JSON separator, we instruct the writer to
quote all fields.
21.1. NullValueHandling
Specifies null value handling options for the ChoJSONWriter
21.2. Formatting
Specifies formatting options for the ChoJSONWriter
21.3 WithFields
This API method specifies the list of JSON fields to be considered for writing JSON
file. Other fields will be discarded. Field names are case-insensitive.
Console.WriteLine(json.ToString());
}
21.4 WithField
This API method used to add JSON column with specific date type, quote flag, and/or
quote character. This method helpful in dynamic object model, by specifying each
and individual JSON column with appropriate datatype.
Console.WriteLine(json.ToString());
}
21.5. IgnoreFieldValueMode
Specifies ignore field value for the ChoJSONWriter
21.6 ColumnCountStrict
This API method used to set the JSONWriter to perform check on column countnness
before writing JSON file.
Console.WriteLine(json.ToString());
}
21.7. Configure
This API method used to configure all configuration parameters which are not
exposed via fluent API.
Console.WriteLine(json.ToString());
}
21.8. Setup
This API method used to setup the writer's parameters / events via fluent API.
Console.WriteLine(json.ToString());
}
License
This article, along with any associated source code and files, is licensed under
The Code Project Open License (CPOL)
Share
About the Author
Cinchoo
United States United States
No Biography provided
Comments and Discussions
Article
View Stats
Revisions (2)
Comments (1)
Posted 8 Jun 2020
Tagged as
C#
.NET
VB.NET
Stats
1.7K views
1 bookmarked
Go to top
Permalink
Advertise
Privacy
Cookies
Terms of Use
Layout: fixed | fluid
Web01 2.8.200606.1