winform - json串的转换

时间:2024-09-03 14:34:27

通过java接口,或者查询数据库返回json串。

可以有两种方式进行解读。

1.简单方式

没有深层结构,最好只有一条数据(当然也可多条)。可以用datatable来获取。返回的是clo0、clo1、clo2...这种标识。

这就要求事先知道列的内容,尤其是自己写的查询语句的时候。

DataTable dt0 = FromRuntime.sqlToDataTables(sql);
//如果有数据
if (dt0.Rows.Count > 0)
{
  //遍历dt0
  for (int i = 0; i < dt0.Rows.Count; i++)
  {
    //填充到列表
    DataList.Add(new DataModel(int.Parse(dt0.Rows[i]["col0"].ToString()), dt0.Rows[i]["col1"].ToString(), dt0.Rows[i]["col2"].ToString()));
  }
}

2.复杂方式

获取字符串后转换成键值对,然后遍历,当然,键值对的key也是事先知道的

string parameter = String.Format("loginUid={0}&id={1}", UserAndSecurity.g_userInfo.id, userAdd.m_userModel.Id);

string stsr = Inth.Https.FromRuntime.GetPageSourceToDataTable2("inth_user_show", parameter);

Dictionary<string, object> dic = Inth.Https.FromRuntime.JsonToDictionary(stsr);

if (dic["code"].ToString() != "SUCCESS")
{
MessageBox.Show(dic["msg"].ToString());
return;
}

Dictionary<string, object> dicData = (Dictionary<string, object>)dic["data"];

int.TryParse(dicData["id"].ToString(), out UserAndSecurity.g_userInfo.id);
UserAndSecurity.g_userInfo.name = dicData["name"].ToString();
UserAndSecurity.g_userInfo.password = dicData["password"].ToString();

//数组列表

ArrayList dicData = (ArrayList)item.Value;

foreach (Dictionary<string, object> itemMenus in dicData)
{

}

调用接口进行操作:

string parameter = String.Format("loginUid={0}&planId={1}&name={2}", UserAndSecurity.g_userInfo.id, m_iPlanId, textBox1.Text);

string stsr = Inth.Https.FromRuntime.GetPageSourceToDataTable2("inth_deliver_fee_add", parameter);

if (stsr.Contains("SUCCESS"))
{
MessageBox.Show("操作完成");
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("操作失败");
this.DialogResult = DialogResult.Cancel;
}