如何使用System.Runtime.Serialization.Json解析此String?

时间:2013-04-09 05:40:15

标签: c# json parsing

您能否帮助我使用System.Runtime.Serialization.Json不是Json.NET )来获取此阵列中每本书的信息:

{
    "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
}

2 个答案:

答案 0 :(得分:11)

这是一个我掀起的快速示例,似乎有效:

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; }
}

我确信你可以调整很多其他选项,但这至少应该让你开始。

答案 1 :(得分:1)

通用方法:

using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace YourApp.Helpers
{
    public class SystemSerializer:ISerializer
    {
        public T Deserialize<T>(string json) where T : class
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                return ser.ReadObject(ms) as T;
            }
        }

        public T Deserialize<T>(Stream json) where T : class
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            return ser.ReadObject(json) as T;
        }

        public async Task<string> SerializeAsync<T>(T obj) where T : class
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (var ms = new MemoryStream())
            {
                ser.WriteObject(ms, obj);
                ms.Position = 0;
                using (var sr = new StreamReader(ms))
                {
                    return await sr.ReadToEndAsync();
                }
            }
        }
    }
}