问题描述
我正在使用 JSON.NET 和 C# 5.我需要将对象列表序列化/反序列化为行分隔的 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}]}
为什么我需要它,因为它的 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
更新:我发现的一种方法是单独序列化每个对象并在最后加入换行符.
Update: One way I found is that serialize each object seperataly and join in the end with new-line.
推荐答案
您可以通过使用 JsonTextReader 手动解析 JSON 并将 SupportMultipleContent 标志设置为 真.
You can do so by manually parsing your JSON using JsonTextReader and setting the SupportMultipleContent flag to true.
如果我们查看您的第一个示例,并创建一个名为 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);
}
如果您想要项目列表作为结果,只需将每个项目添加到 while 循环内的列表中即可.
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));
注意:对于 Json.Net 10.0.4 及更高版本,相同的代码还支持逗号分隔的 JSON 条目,请参阅 如何反序列化狡猾的 JSON(带有不正确引用的字符串和缺少括号)?)
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)?)
这篇关于行分隔的 json 序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)