C#解析json数据

引用地址:https://www.jb51.net/article/129571.htm

一、需要引用System.Web.Extensions 

//根据key获取对应值
public static bool GetValue(string json, string key, out string value)
{
  value = "";
  JavaScriptSerializer serializer = new JavaScriptSerializer();
  try
  {
    Dictionary<string, object> obj_json = serializer.DeserializeObject(json) as Dictionary<string, object>;
    if (obj_json.ContainsKey(key))
    {
      value = serializer.Serialize(obj_json[key]);
      return true;
    }
    return false;
  }
  catch (Exception)
  {
    return false;
  }
}
//根据index获取值
public static bool GetValue(string json, int index, out string value)
{
  value = "";
  JavaScriptSerializer serializer = new JavaScriptSerializer();
  try
  {
    object[] obj_json = serializer.DeserializeObject(json) as object[];
    if (obj_json.Length > index)
    {
      value = serializer.Serialize(obj_json[index]);
      return true;
    }
    return false;
  }
  catch (Exception)
  {
    return false;
  }
}

posted @ 2020-09-28 15:10  Morning=Sunshine  阅读(76)  评论(0)    收藏  举报