可以使用开源的类库Newtonsoft.Json。
例如解析如下
string json =
{
"result": "ok", // ret 值为 ok 时 返回 data 数据 为err时返回msg数据
"data": [
"ava", /
"ben",
"ccc",
"ddd",
]
};
函数如下
public string cutJson(string json,string item,int index)
{
JObject jo = (JObject)JsonConvert.DeserializeObject(json);
string value = jo[item][index].ToString();
return value;
}
其中item表示为Json中的key(名称), index表示某个item对应的value(值对)中的特定项
拓展:
Api接口接受Post过来的查询条件并返回数据
Post查询条件 (用Postman放在Body里调试)
{
"PN": "ABCDEFGHIJ-00",
"cuPNList": [
{
"cuPN": "9A200000000000000"
} ,
{
"cuPN": "900000000030000"
}
]
}
Api接口
1 [HttpGet] 2 [Route("api/GetLotCardMIMAFInfo")] 3 public HttpResponseMessage GetLotCardMIMAFInfo() 4 { 5 var data = Request.Content.ReadAsStringAsync().Result; 6 var PNlist = ""; 7 JObject jsonObj = JObject.Parse(data); 8 string PNno = jsonObj["PN"].ToString(); 9 10 JArray jsonAry = JArray.Parse(jsonObj["cuPNList"].ToString()); 11 JObject stu1Obj = JObject.Parse(jsonAry[0].ToString()); 12 string cuPN = stu1Obj["cuPN"].ToString(); 13 foreach (var ss in jsonAry) //查找某个字段与值 14 { 15 PNlist = PNlist + ss["cuPN"].ToString() + ","; // ((JObject)ss)["cuPN"]; // JObject.Parse(jsonAry[0].ToString()); 16 } 17 JsonData jd = new JsonData(); 18 //JavaScriptSerializer js = new JavaScriptSerializer(); 19 //var resultqq = JsonConvert.DeserializeObject<List<PNitem>>(cuPNList); 20 //List<PNitem> lst = js.Deserialize<List<PNitem>>(cuPNList); 21 //var PNlist = ""; 22 //for (int i = 0; i < lst.Count; i++) 23 //{ 24 // PNlist = PNlist + lst[i].cuPN +","; 25 //} 26 DataTable dt = checkInplanservice.GettLotCardInfoTable(PNno); 27 DataTable dtMAF = checkInplanservice.GettLotCardMAFInfoTable(PNlist); 28 //OBJ转化成JSON 29 jd.Status = HandleStatus.Success; 30 jd.Data = new 31 { 32 cuLayerType = dt.Rows[0]["LayerLevel"], 33 cuCustomer = dt.Rows[0]["MiCustPn"], 34 cuCustomerName = dt.Rows[0]["MiCustName"], 35 cuQRCustomerPN = "", 36 cuQRCustomerPNVersion = "", 37 cuPNLOrigin = dt.Rows[0]["lvdr"], 38 cuSize = dt.Rows[0]["Value"], 39 cuCurrSize = dt.Rows[0]["MiSetArea"], 40 cuHSFRequirement = dt.Rows[0]["AttrCode"], 41 cuPNList = dtMAF, 42 test= new[] {new {Name ="Tom",Age=30}, 43 new {Name ="Lily", Age=22}} 44 }; 45 string msgAll = JsonConvert.SerializeObject(jd); 46 return JsonResult(msgAll); 47 48 49 //string json = JsonConvert.SerializeObject(dt); 50 ////返回json数 51 //return new HttpResponseMessage() 52 //{ 53 // Content = new StringContent(json, Encoding.UTF8, "application/json"), 54 //}; 55 56 }