使用LitJSON操作json数据

网址:​​https://litjson.net/​

dll下载地址

示例

字符串生成JsonData对象

JsonData obj = JsonMapper.ToObject(jsonStr);

结合实体对象生成json

using LitJson;
using System;

public class Person
{
// C# 3.0 auto-implemented properties
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}

public class JsonSample
{
public static void Main()
{
PersonToJson();
JsonToPerson();
}

public static void PersonToJson()
{
Person bill = new Person();

bill.Name = "William Shakespeare";
bill.Age = 51;
bill.Birthday = new DateTime(1564, 4, 26);

string json_bill = JsonMapper.ToJson(bill);

Console.WriteLine(json_bill);
}

public static void JsonToPerson()
{
string json = @"
{
""Name"" : ""Thomas More"",
""Age"" : 57,
""Birthday"" : ""02/07/1478 00:00:00""
}";

Person thomas = JsonMapper.ToObject<Person>(json);

Console.WriteLine("Thomas' age: {0}", thomas.Age);
}
}

节点属性

node["attribute"]

键是否存在

if (((IDictionary)jd).Contains("KeyName")) {
string valuestr = (string)jd["KeyName"];
}

生成json字符串

Hashtable result = new Hashtable();
result["moveup_dir_path"] = moveupDirPath;
context.Response.Write(JsonMapper.ToJson(result));

其它有用代码

param转json字符串

private string str2json(string str)
{
var result = "{";
string[] oneitem = str.Split('&');
foreach (string item in oneitem)
{
if (item.Trim() == "") continue;
string[] v = item.Split('=');
result += "'" + v[0] + "':";
if (v.Count() == 2)
result += "'" + v[1] + "'";
else
result += "''";
result += ",";
}
result = result.TrimEnd(',') + "}";
return result;
}

ASP.NET JSONObject

使用方法参见

GIT地址:​​https://github.com/CCwant/ForceJson​

DLL地址

Newtonsoft.Json.dll

开源类库。

使用JavaScriptSerializer类

System.Runtime.Serialization.dll

提供的DataContractJsonSerializer或者 JsonReaderWriterFactory实现。