C# 对象转JSON和json转对象(转出为dynamic的对象)

/// <summary>
    /// json转换工具
    /// </summary>
    public class JsonTools
    {
        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// JSON转对象 ,获得dynamic类型的对象
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static dynamic JsonToObject(string jsonString)
        {
            return JsonConvert.DeserializeObject<dynamic>(jsonString);
        }
    }

遍历dynamic属性及值
  string jsonStr = "{\"idCard\":3021552,\"name\":\"adan \",\"age\":\"33 \"}";
                var obj = JObject.Parse(jsonStr);// JsonConvert.DeserializeObject<dynamic>(jsonStr);
                var res = obj.Children().OfType<JProperty>();
                foreach(var item in res)
                {
                    string name = item.Name;
                    var value = item.Value;
                }

 

 

 

posted @ 2019-03-24 15:39  巴蒂尔  阅读(830)  评论(0编辑  收藏  举报