問(wèn)題描述
我正在使用 JSON.NET 和 C# 5.我需要將對(duì)象列表序列化/反序列化為行分隔的 json.http://en.wikipedia.org/wiki/Line_Delimited_JSON.例如,
I am using JSON.NET and C# 5. I need to serialize/de-serialize list of objects into line delimited json. http://en.wikipedia.org/wiki/Line_Delimited_JSON. Example,
{"some":"thing1"}
{"some":"thing2"}
{"some":"thing3"}
和
{"kind": "person", "fullName": "John Doe", "age": 22, "gender": "Male", "citiesLived": [{ "place": "Seattle", "numberOfYears": 5}, {"place": "Stockholm", "numberOfYears": 6}]}
{"kind": "person", "fullName": "Jane Austen", "age": 24, "gender": "Female", "citiesLived": [{"place": "Los Angeles", "numberOfYears": 2}, {"place": "Tokyo", "numberOfYears": 2}]}
為什么我需要它,因?yàn)樗?Google BigQuery 要求 https://cloud.google.com/bigquery/preparing-data-for-bigquery
Why I needed because its Google BigQuery requirement https://cloud.google.com/bigquery/preparing-data-for-bigquery
更新:我發(fā)現(xiàn)的一種方法是單獨(dú)序列化每個(gè)對(duì)象并在最后加入換行符.
Update: One way I found is that serialize each object seperataly and join in the end with new-line.
推薦答案
您可以通過(guò)使用 JsonTextReader
手動(dòng)解析 JSON 并將 SupportMultipleContent
標(biāo)志設(shè)置為 真
.
You can do so by manually parsing your JSON using JsonTextReader
and setting the SupportMultipleContent
flag to true
.
如果我們查看您的第一個(gè)示例,并創(chuàng)建一個(gè)名為 Foo
的 POCO:
If we look at your first example, and create a POCO called Foo
:
public class Foo
{
[JsonProperty("some")]
public string Some { get; set; }
}
這就是我們解析它的方式:
This is how we parse it:
var json = "{"some":"thing1"}
{"some":"thing2"}
{"some":"thing3"}";
var jsonReader = new JsonTextReader(new StringReader(json))
{
SupportMultipleContent = true // This is important!
};
var jsonSerializer = new JsonSerializer();
while (jsonReader.Read())
{
Foo foo = jsonSerializer.Deserialize<Foo>(jsonReader);
}
如果您想要項(xiàng)目列表作為結(jié)果,只需將每個(gè)項(xiàng)目添加到 while
循環(huán)內(nèi)的列表中即可.
If you want list of items as result simply add each item to a list inside the while
loop to your list.
listOfFoo.Add(jsonSerializer.Deserialize<Foo>(jsonReader));
注意:對(duì)于 Json.Net 10.0.4 及更高版本,相同的代碼還支持逗號(hào)分隔的 JSON 條目,請(qǐng)參閱 如何反序列化狡猾的 JSON(帶有不正確引用的字符串和缺少括號(hào))?)
Note: with Json.Net 10.0.4 and later same code also supports comma separated JSON entries see How to deserialize dodgy JSON (with improperly quoted strings, and missing brackets)?)
這篇關(guān)于行分隔的 json 序列化和反序列化的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!