最近写了C#代码,然而C#操作json的方式实在是不习惯,于是就模仿Java解析json的写法做了一层封装。
引用库:Newtonsoft.Json
JSONObject:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JSONPackaging {
public class JSONObject {
private JObject jObject;
private JSONObject(JObject jObject) {
this.jObject = jObject;
}
public JSONObject() {
this.jObject = new JObject();
}
public static JSONObject StringParseJSON(string str) {
JObject jo = JsonConvert.DeserializeObject(str) as JObject;
JSONObject j = new JSONObject(jo);
return j;
}
public string GetString(string key) {
return (string)jObject[key];
}
public int GetInt(string key) {
return (int)jObject[key];
}
public void Put(string key,string value) {
CheckJobject();
jObject[key] = value;
}
private void CheckJobject() {
if(jObject == null) {
jObject = new JObject();
}
}
private string WipeOffCarriageReturn(string str) {
return str.Replace("\r", "").Replace("\n", "").Replace(" ", "");
}
public void Put(string key,int value) {
CheckJobject();
jObject[key] = value;
}
public void Put(string key,JSONArray jsonArray) {
jObject[key] = JArray.Parse(jsonArray.ToString());
}
public override string ToString() {
string str = jObject.ToString();
return WipeOffCarriageReturn(str).Trim();
}
public JSONArray GetJsonArray(string key) {
return JSONArray.Parse(jObject[key].ToString());
}
}
}
JSONArray:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JSONPackaging {
public class JSONArray {
private JArray jArray;
public int Count { get; private set; }
public JSONArray() {
this.jArray = new JArray();
}
private JSONArray(JArray j) {
this.jArray = j;
}
public static JSONArray Parse(string str) {
JArray jrr = JArray.Parse(str);
JSONArray j = new JSONArray(jrr);
j.Count = jrr.Count;
return j;
}
public JSONObject GetIndex(int i) {
return JSONObject.StringParseJSON(jArray[i].ToString());
}
public void Add(JSONObject jsonObject) {
this.jArray.Add((JObject)JsonConvert.DeserializeObject(jsonObject.ToString()));
Count = jArray.Count;
}
public void Clear() {
this.jArray.Clear();
}
private string WipeOffCarriageReturn(string str) {
return str.Replace("\r", "").Replace("\n", "").Replace(" ", "");
}
public override string ToString() {
string str = jArray.ToString();
return WipeOffCarriageReturn(str).Trim();
}
}
}