C# 使用第三方函式庫來存取JSON
C# 使用第三方函式庫來存取JSON
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
Newtonsoft.Json;//使LI用DI外D~部!函Lc式!庫w- Newtonsoft.Json.dll (VS2010- .net4.0 )
//資Me料A來LO源P?:http://lolikitty.pixnet.net/blog/post/134553560-unity-c%23-json-%E7%B7%A8%E7%A2%BC%E3%80%81%E8%A7%A3%E7%A2%BC-(%E4%BD%BF%E7%94%A8-json.net)
namespace
CS_Console_Json
{
/*
//簡2單a版c
public class Book
{
public int ID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
}
*/
public class Book
{
public int ID;
public string Name;
public string Author;
public List<string>
ListData =
new List<string>();
}
public class RootLibrary
{
// Value name
(Library) is Json root “Name”.
public List<Book>
Library =
new List<Book>();
}
class Program
{
static void Main(string[]
args)
{
/*
//簡2單a版c
Book book = new Book();
book.ID = 1;
book.Name = “Push Loli (
Getting Started )”;
book.Author = “Alice”;
// Json Encoding
string output =
JsonConvert.SerializeObject(book);
Console.WriteLine(output);
Book book2 =
JsonConvert.DeserializeObject<Book>(output);
Console.WriteLine(“ID : ”
+ book2.ID);
Console.WriteLine(“Name :
” + book2.Name);
Console.WriteLine(“Author :
” + book2.Author);
*/
// Json
Path : Library.book
Book
book = new Book
();
book.ID = 1;
book.Name = “Unity Book”;
book.Author = “Bee”;
book.ListData.Add (“Box”);
book.ListData.Add (“Banana”);
book.ListData.Add (“Ball”);
// Json
Path : Library.book2
Book
book2 = new Book
();
book2.ID = 2;
book2.Name = “C# Book”;
book2.Author = “God”;
book2.ListData.Add (“Man”);
book2.ListData.Add (“Boy”);
book2.ListData.Add (“Girl”);
// Json
Path : Library.book3
Book
book3 = new Book
();
book3.ID = 3;
book3.Name = “Loli Book”;
book3.Author = “Alice”;
book3.ListData.Add (“Cat”);
book3.ListData.Add (“Dog”);
book3.ListData.Add (“Apple”);
// Json
Path : Library (Root)
RootLibrary
lib = new RootLibrary();
lib.Library.Add(book);
lib.Library.Add(book2);
lib.Library.Add(book3);
// Json
Encoding
string
output = JsonConvert.SerializeObject(lib);
Console.WriteLine(output);
//————————————————————–
// Json
Decoding
RootLibrary
_lib = JsonConvert.DeserializeObject<RootLibrary> (output);
foreach
(Book _book in
_lib.Library)
{
Console.WriteLine(“———————————-“);
Console.WriteLine(“ID : “ + _book.ID);
Console.WriteLine(“Name : “ + _book.Name);
Console.WriteLine(“Author : “ + _book.Author);
for
(int i = 0; i < _book.ListData.Count; i++)
{
Console.WriteLine(“ListData [ “ + i + ” ] : “ + _book.ListData[i]);
}
}
Pause();
}
static void Pause()
{
Console.Write(“Press any key to continue . . . “);
Console.ReadKey(true);
}
}
}