0

I have the following code which uses Json.net:

class HistorianRecord
{
    public string tagname { get; set; }
    public string engunits { get; set; }
    public string value { get; set; }
    public string quality { get; set; }
    public DateTime timestamp { get; set; }
}

private static void createJSONFile(DataTable dt)
{
    var HistorianData = new List<HistorianRecord>();

    foreach(DataRow row in dt.Rows)
    {
        HistorianData.Add(new HistorianRecord()
        {
            tagname = row["tagname"].ToString(),
            engunits = row["engunits"].ToString(),
            value =  row["value"].ToString(),
            quality = row["quality"].ToString(),
            timestamp = DateTime.Parse(row["timestamp"].ToString())
        });
    }

    var serializer = new JavaScriptSerializer();
    var serializedResult = serializer.Serialize(HistorianData);
    var deserializedResult = serializer.Deserialize<List<HistorianRecord>>(serializedResult);

    File.WriteAllText(folderPath + fileName, JsonConvert.SerializeObject(deserializedResult));
}

Which produces the following JSON file, which I have shortened for this post as the are > 1000 rows in the datatable:

[
  {
    "tagname": "mytag1",
    "engunits": "",
    "value": "2",
    "quality": "Good NonSpecific",
    "timestamp": "2018-12-13T10:45:05Z"
  },
  {
    "tagname": "myTag2",
    "engunits": "",
    "value": "0",
    "quality": "Good NonSpecific",
    "timestamp": "2018-12-13T10:45:00Z"
  }
]

I would like to amend my code to so I can add some items at the beginning of the JSON file so it looks more like this:

[
  {
    "name": "ARandomName",
    "content": [
      {
        "tagname": "mytag1",
        "engunits": "",
        "value": "2",
        "quality": "Good NonSpecific",
        "timestamp": "2018-12-13T10:45:05Z"
      },
      {
        "tagname": "myTag2",
        "engunits": "",
        "value": "0",
        "quality": "Good NonSpecific",
        "timestamp": "2018-12-13T10:45:00Z"
      }
    ]
  }
]

This is so I can create some documents for a test MongoDB installation that I am investigating so all help is appreciated.

1 Answer 1

1

You simply can wrap your deserialized list of HistorianRecords in an anonymous object and reserialize it:

var anon = new 
{
    name = "ARandomName",
    content = deserializedResult 
};

string newJson = JsonConvert.SerializeObject(anon, Formatting.Indented);

Fiddle: https://dotnetfiddle.net/6kSvxS

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.