Reputation: 23
I'm using a simple Desearialization of json using NewtonSoft.json:
Private Sub Deserialize()
Dim json As String = ""
Try
Using sr As StreamReader = New StreamReader("C:\Temp\file.json")
json = sr.ReadToEnd
End Using
dataset= JsonConvert.DeserializeObject(Of DataSet)(json)
Catch ex As Exception
End Try
End Sub
The dataset is predefined in the vb code. The customer now wants to add 5 more columns to a datatable inside the dataset. I define the columns in that table, but when the deserializing occurs, the datatable columns are overwritten back to the original state, that is, without the new columns.
Datatables are always having columns added and removed. That's business. With thousands of existing records with the original json layouts, how to I load the data without changing the existing data structure, and allow users to add the data to the new columns?
I'm new to json, and would appreciate any help available.
Upvotes: 2
Views: 328
Reputation: 17001
You serialized a DataSet
with a specific schema, you are going to get that exact schema back out when you deserialize it. That's just how serialization works. If you have an existing DataSet
that you want to merge in, or extra columns you want to add after deserialization, you will have to do that programatically.
In your example code, assuming dataset
is the existing DataSet
, you would want to deserialize to a new, temporary DataSet
, then walk through that, fixing up the schema as needed, then merging it in to your existing DataSet
row by row.
If your schema is dynamic, you will have to store some meta-data about the columns in a list somewhere. At minimum, the column name and type. After deserializing, you can walk that list for any columns that are missing from the DataSet
, create the columns with the correct type programatically, and add them in.
There is a DataSet.Merge
method that may help you out, it has some options for how to handle missing schema.
When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.
It may be as simple as replacing your deserialization line with:
dataset.Merge(JsonConvert.DeserializeObject(Of DataSet)(json), true, MissingSchemaAction.AddWithKey)
Upvotes: 2