將Json載入到.NET物件並對結果進行過濾和排序

風靈使發表於2019-01-01

Program.cs

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace JsonFilterSort
{
	internal class Program
	{
		
		private static void Main(string[] args)
		{
			string url = @"http://agl-developer-test.azurewebsites.net/people.json";
			var client = new System.Net.WebClient();

			ParseJsonToObject(client.DownloadString(url));
		}

        /// <summary>
        ///將json解析為物件
        /// </summary>
        /// <param name="json">The json string.</param>
        public static void ParseJsonToObject(string json)
		{
			JArray jsonArray = JArray.Parse(json);

            //將Json載入到.Net物件
            IList<Owner> owners = jsonArray.Select(x => new Owner
			{
				Name = (string)x["name"],
				Gender = (string)x["gender"],
				Age = (int)x["age"],
				Pets = (x["pets"]).Select(p => new Pet { PetName = (string)p["name"], PetType = (string)p["type"] }).ToList()
			}
			).ToList();

			Console.WriteLine("Male");

            //列印 Male owners擁有的所有貓
            //可以轉換為單個Linq語句
            foreach (var item in owners.Where(p => p.Gender == "Male"))
			{
				foreach (var pet in item.Pets.Where(p => p.PetType == "Cat").OrderBy(x => x.PetName))
				{
					Console.WriteLine("-" + pet.PetName);
				}
			}

			Console.WriteLine("Female");

            // Print all cats owned by
            //列印  Female owners擁有的所有貓
            foreach (var item in owners.Where(p => p.Gender == "Female"))
			{
				foreach (var pet in item.Pets.Where(p => p.PetType == "Cat").OrderBy(x => x.PetName))
				{
					Console.WriteLine("-" + pet.PetName);
				}
			}
			
			Console.WriteLine("按任意鍵繼續...");
			Console.ReadKey();
		}
	}

	/// <summary>
	/// Owner 類
	/// </summary>
	public class Owner
	{
		public string Name { get; set; }

		public string Gender { get; set; }

		public int Age { get; set; }

		/// </value>
		public List<Pet> Pets { get; set; }
	}

	/// <summary>
	/// Pet 類
	/// </summary>
	public class Pet
	{
		public string PetName { get; set; }

		public string PetType { get; set; }
	}
}

people.json

[
  {
    "name": "Bob",
    "gender": "Male",
    "age": 23,
    "pets": [
      {
        "name": "Garfield",
        "type": "Cat"
      },
      {
        "name": "Fido",
        "type": "Dog"
      }
    ]
  },
  {
    "name": "Jennifer",
    "gender": "Female",
    "age": 18,
    "pets": [
      {
        "name": "Garfield",
        "type": "Cat"
      }
    ]
  },
  {
    "name": "Steve",
    "gender": "Male",
    "age": 45,
    "pets": null
  },
  {
    "name": "Fred",
    "gender": "Male",
    "age": 40,
    "pets": [
      {
        "name": "Tom",
        "type": "Cat"
      },
      {
        "name": "Max",
        "type": "Cat"
      },
      {
        "name": "Sam",
        "type": "Dog"
      },
      {
        "name": "Jim",
        "type": "Cat"
      }
    ]
  },
  {
    "name": "Samantha",
    "gender": "Female",
    "age": 40,
    "pets": [
      {
        "name": "Tabby",
        "type": "Cat"
      }
    ]
  },
  {
    "name": "Alice",
    "gender": "Female",
    "age": 64,
    "pets": [
      {
        "name": "Simba",
        "type": "Cat"
      },
      {
        "name": "Nemo",
        "type": "Fish"
      }
    ]
  }
]

執行結果如圖:

在這裡插入圖片描述

相關文章