如何使用System.Runtime.Serialization.Json解析此String? [英] How to parse this String using System.Runtime.Serialization.Json?
本文介绍了如何使用System.Runtime.Serialization.Json解析此String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您能帮我如何使用System.Runtime.Serialization.Json
(不是Json.NET
)获取此数组中每本书的信息:
Can you help me how to use System.Runtime.Serialization.Json
(not Json.NET
) to get information of each book in this tring to array:
{
"books":
[
{"name":"Book 1","orig":"Author 1","date":2009,"lang":"en"},
{"name":"Book 2","orig":"Author 2","date":2012,"lang":"fr"}
],
"src":"lib",
"id":212
}
推荐答案
以下是我整理的一个快速示例,看起来很有效:
Here's a quick sample I whipped up which appears to work:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
class Test
{
static void Main()
{
using (Stream stream = File.OpenRead("test.json"))
{
var serializer = new DataContractJsonSerializer(typeof(Library));
Library library = (Library) serializer.ReadObject(stream);
Console.WriteLine(library.Books[0].Name);
}
}
}
[DataContract]
class Book
{
[DataMember(Name="name")] public string Name { get; set; }
[DataMember(Name="orig")] public string Orig { get; set; }
[DataMember(Name="date")] public string Date { get; set; }
[DataMember(Name="lang")] public string Lang { get; set; }
}
[DataContract]
class Library
{
[DataMember(Name="books")] public IList<Book> Books { get; set; }
[DataMember(Name="src")] public string Src { get; set; }
[DataMember(Name="id")] public string Id { get; set; }
}
我确定您还有很多其他可以调整的选项,但这至少应该可以让您入门.
I'm sure there are plenty of other options you can tweak, but that should at least get you started.
这篇关于如何使用System.Runtime.Serialization.Json解析此String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文