Json是一种轻量级数据交换格式,是一种理想的数据交换语言,易于理解和编写。
Json可以分为两部分:
1、Json Object(A Collection of name/value pairs)
2、Json Array(An ordered list of values)
使用LitJson解析Json。
using System.Text;
using System.Threading.Tasks;
using LitJson;
namespace LitJsonTest
{
class Program
{
static void Main(string[] args)
{
string str = "{'name':'cyf', 'id':10, 'items':[{'itemid':1001, 'itemname':'hello'},{'itemid':1002, 'itemname':'hello2'}]}";
//************读取Json字符串中的数据***********
JsonData jd = JsonMapper.ToObject(str);
string name = (string) jd["name"];
Console.WriteLine("name: " + name);
long id = Convert.ToInt64(jd["id"].ToString());
Console.WriteLine("id: " + id);
JsonData jdItems = jd["items"];
Console.WriteLine("items: ");
int itemCnt = jdItems.Count;
foreach (JsonData item in jdItems)
{
int itemID = (int) item["itemid"];
string itemName = (string) item["itemname"];
Console.WriteLine("\titemid: " + itemID);
Console.WriteLine("\titemname: " + itemName);
Console.WriteLine();
}
//string str2 = jd.ToJson();
Console.Read();
}
}
}
创建Json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;
namespace LitJsonTest
{
class Program
{
static void Main(string[] args)
{
JsonData data = new JsonData();
data["URL"] = "http;//localhost/index.php";
data["AssetList"] = new JsonData();
data["AssetList"]["id"] = 1;
data["AssetList"]["name"] = "rechard";
data["items"] = new JsonData();
JsonData book01 = new JsonData();
book01["id"] = 1;
book01["name"] = "Math";
JsonData book02 = new JsonData();
book02["id"] = 2;
book02["name"] = "Englist";
data["items"].Add(book01);
data["items"].Add(book02);
string json_str = data.ToJson();
Console.WriteLine(json_str);
Console.Read();
}
}
}
输出结果: