行分隔的 json 序列化和反序列化

时间:2023-04-27
本文介绍了行分隔的 json 序列化和反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在使用 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 序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:我可以在属性中指定路径以将我的类中的属性映射到我的 JSON 中的子属性吗? 下一篇:.Net Core 3.0 中的 IMvcBuilder AddJsonOptions 去了哪里?

相关文章