如何在C#中使用JsonWriter对嵌套集合进行序列化

我需要使用JSON生成与XML相同的输出

对于Excel工作表中的某些表格数据,数据格式为:

Column1 Column2 Column3 AAA bbb ccc XXX YYY ZZZ kkk jjj nnn 

我需要编写Json文件使用Json编写器,因为我不能创build一个类来产生数据,但是我已经使用创build的JSON反序列化它作为一个不同的应用程序中的类。 为了能够在消费者应用程序中反序列化类,我需要一个类,我们可以将其命名为MyClass,其中包含一个Items集合,每个Item表示一个Row,标题Column1,Column2,Column3是属性的名称。

我已经能够产生这个:

 { "Item": { "Column1": "AAA", "Column2": "BBB", "Column3": "CCC", }, "Item": { "Column1": "XXX", "Column2": "YYY", "Column3": "ZZZ", }, } 

不幸的是,这不是一个包含项目集合的对象,所以它不反序列化。

这是我用来从excel文件手动序列化的代码,我无法find的是如何脚本的集合的开始和结束:

 StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonWriter jsonWriter = null; jsonWriter = new JsonTextWriter(sw); jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; jsonWriter.WriteStartObject(); int countAwait = 0; // Here I miss what to write to open the collection for (int row = firstRow; row <= end.Row; row++) { count++; countAwait++; if (countAwait >= 10) { ResultText = "Reading record " + count; countAwait = 0; } jsonWriter.WritePropertyName(RowElement); jsonWriter.WriteStartObject(); for (int col = start.Column; col <= end.Column; col++) { jsonWriter.WritePropertyName(fieldNames[col]); jsonWriter.WriteValue(GetCellStringValue(ws, row, col)); } jsonWriter.WriteEndObject(); } // Here I need to write the closing of the collection jsonWriter.WriteEndObject(); jsonWriter.Close(); 

编辑添加Json序列化程序如何序列化我的目标类的样本:

 { "Items": [ { "Column1": "XXX", "Column2": "YYY", "Column3": "ZZZ", }, { "Column1": "AAA", "Column2": "BBB", "Column3": "CCC", } ] } 

该类是MyClass并包含typesItem的类的集合项。

您应该只写属性名称"Items"一次,然后为它的值使用JsonWriter.WriteStartArray()JsonWriter.WriteEndArray()来启动和结束一个JSON数组,然后将每行作为一个嵌套在数组中的对象写入:

 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 } 

(这里我假定RowElement对应于"Items"string。)