4

你能帮我如何使用System.Runtime.Serialization.Json( notJson.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
}
4

2 回答 2

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

我确信您可以调整许多其他选项,但这至少应该让您入门。

于 2013-04-09T05:50:31.583 回答
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();
                }
            }
        }
    }
}
于 2018-03-23T12:03:21.243 回答