使用.NETFramework3.5/4.0中提供的System.Web.Script.Serialization命名空间下的JavaScriptSerializer类进行对象的序列化与反序列化,很直接。要求当前的工程的TargetFramework要改成.Net Framework 4,不能使用Client Profile。
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> dic = (Dictionary<string,object>)serializer.DeserializeObject(json);
if (dic.ContainsKey("键值"))
dic["键值"].ToString();
使用开源的类库Newtonsoft.Json
- 使用JsonReader读Json字符串
string jsonText = @"{""input"" : ""value"", ""output"" : ""result""}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
while (reader.Read())
{
Console.WriteLine(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value);
}
- 使用JsonSerializer读写对象(基于JsonWriter与JsonReader)
数组型数据
string jsonArrayText1 = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]";
JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);
string ja1a = ja[1]["a"].ToString();
//或者
JObject o = (JObject)ja[1];
string oa = o["a"].ToString();
- 嵌套格式
string jsonText = "{\"beijing\":{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}}";
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
string zone = jo["beijing"]["zone"].ToString();
string zone_en = jo["beijing"]["zone_en"].ToString();
- DataTable 转换成 Json
using Newtonsoft.Json;
public string DataTableToJsonWithJsonNet(DataTable table)
{
string JsonString=string.Empty;
JsonString = JsonConvert.SerializeObject(table);
return JsonString;
//反序列化
//DataTable api_Table = Newtonsoft.Json.JsonConvert.DeserializeObject(text,typeof(DataTable)) as DataTable;
}
自定义类
DataserviceParam p = new DataserviceParam() { tableName = "tableName", schema = "schema" };//写入
JsonSerializer serializer = new JsonSerializer();
StringWriter sw = new StringWriter();
serializer.Serialize(new JsonTextWriter(sw), p);
string Jsondata = sw.GetStringBuilder().ToString();
Console.WriteLine(Jsondata);//打印
//输出
FileStream fs = File.Open(strJsonPath, FileMode.OpenOrCreate, FileAccess.Write);//pathJson
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0); //清空txt文件
StreamWriter sw = new StreamWriter(fs);
Jsondata=ConvertJsonString(str);
sw.Write(Jsondata);
sw.Flush();
sw.Close();
fs.Close();
DataserviceParam lstjsonDeserialize = JsonConvert.DeserializeObject<DataserviceParam>(json);
string tableName = lstjsonDeserialize.tableName;//按键名输出
public class DataserviceParam
{
/// <summary>
/// 表名
/// </summary>
public string tableName { get; set; }
/// <summary>
/// 模式
/// </summary>
public string schema { get; set; }
/// <summary>
/// 数据id
/// </summary>
public string dataId { get; set; }
/// <summary>
/// 地图id
/// </summary>
public string mapId { get; set; }
/// <summary>
/// 数据过滤条件
/// </summary>
public string filter { get; set; }
}
/// <summary>
/// json规格化
/// </summary>
/// <param name="str">json串</param>
/// <returns></returns>
public static string ConvertJsonString(string str)
{
JsonSerializer serializer = new JsonSerializer();
TextReader tr = new StringReader(str);
JsonTextReader jtr = new JsonTextReader(tr);
object obj = serializer.Deserialize(jtr);
if (obj != null)
{
StringWriter textWriter = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar = ' '
};
serializer.Serialize(jsonWriter, obj);
return textWriter.ToString();
}
else
{
return str;
}
}
额外说明:sql在存储json时需要把json中的单引号替换为双引号
strjJson = strjJson.Replace("\'", "\"");