线分隔的JSON序列化和反序列化 [英] Line delimited json serializing and de-serializing

查看:203
本文介绍了线分隔的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}]}

为什么我需要的,因为它的谷歌的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

更新:我发现的一种方式是,序列化每个seperataly对象,并与新线年底加入

Update: One way I found is that serialize each object seperataly and join in the end with new-line.

推荐答案

您可以通过使用手动解析你的JSON JsonTextReader 并设置<$ C这样做$ C> SupportMultipleContent 标志真正

You can do so by manually parsing your JSON using JsonTextReader and setting the SupportMultipleContent flag to true.

如果我们看一下你的第一个例子,并创建一个POCO名为

If we look at your first example, and create a POCO called Foo:

public class Foo
{
    [JsonProperty("some")]
    public string Some { get; set; }
}

这是我们如何分析它:

var json = "{\"some\":\"thing1\"}\r\n{\"some\":\"thing2\"}\r\n{\"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);
}

这篇关于线分隔的JSON序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆