howto Serialize a Nested collection using JsonWriter in C#

前端 未结 1 1112
被撕碎了的回忆
被撕碎了的回忆 2021-01-16 23:33

I need to produce the same output I produce in XML using JSON

For some tabular data that is in an Excel Worksheet, data is in the format:

Column1 Col         


        
相关标签:
1条回答
  • 2021-01-17 00:07

    You should write the property name "Items" only once, then for its value use JsonWriter.WriteStartArray() and JsonWriter.WriteEndArray() to start and end a JSON array, then write each row as an object nested in the array:

    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    using (var jsonWriter = new JsonTextWriter(sw))
    {
        var countAwait = 0;
    
        jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
        jsonWriter.WriteStartObject(); // Write the opening of the root object
        jsonWriter.WritePropertyName(RowElement); // Write the "Items" property name
        jsonWriter.WriteStartArray(); // Write the opening of the "Items" array
    
        for (int row = firstRow; row <= end.Row; row++)
        {
            count++;
            countAwait++;
            if (countAwait >= 10)
            {
                ResultText = "Reading record " + count;
                countAwait = 0;
            }
            jsonWriter.WriteStartObject(); // Write the beginning of an entry in the "Items" array
            for (int col = start.Column; col <= end.Column; col++)
            {
                jsonWriter.WritePropertyName(fieldNames[col]);
                jsonWriter.WriteValue(GetCellStringValue(ws, row, col));
    
            }
            jsonWriter.WriteEndObject(); // Write the ending of an entry in the "Items" array
        }
    
        jsonWriter.WriteEndArray(); // Write the closing of the "Items" array.
        jsonWriter.WriteEndObject(); // Write the closing of the root object
        // No need to close explicitly when inside a using statement
    }
    

    (Here I am assuming that RowElement corresponds to the "Items" string.)

    0 讨论(0)
提交回复
热议问题