當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
JSON——Json对象扁平化
生活随笔
收集整理的這篇文章主要介紹了
JSON——Json对象扁平化
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一個(gè)層級(jí)結(jié)構(gòu)很深的json對(duì)象
下面的代碼是JSON扁平化的幫助類(lèi):聲明:
代碼如下:
using System.Collections.Generic; using Newtonsoft.Json.Linq;namespace MongoDBAccess {public class JsonHelper{private readonly List<string> _keys = new List<string>();public string ToFlat(JObject obj, string parent){string result = null;foreach (var item in obj){if (typeof(JObject) == item.Value.GetType()){var child = (JObject)item.Value;var tmp = ToFlat(child, item.Key);result += tmp;}else if (typeof(JArray) == item.Value.GetType()){var jarray = (JArray)item.Value;if (jarray.Count == 0 && !_keys.Contains(item.Key)){result += string.Format("'{0}':{1},", item.Key, new JArray());_keys.Add(item.Key);}else{foreach (var jitem in jarray){if (jitem.HasValues){var jchild = (JObject)jitem;string tmp = ToFlat(jchild, item.Key);result += tmp;}else if(!_keys.Contains(item.Key)){result += string.Format("'{0}':{1},", item.Key, new JArray(){jitem});_keys.Add(item.Key);}}}}else{var value = item.Value ?? " ";if (string.IsNullOrEmpty(parent) && !_keys.Contains(item.Key)){result += string.Format("'{0}':\"{1}\",", item.Key, value);_keys.Add(item.Key);}else if (!_keys.Contains(parent + "_" + item.Key)){result += string.Format("'{0}_{1}':'{2}',", parent, item.Key, value);_keys.Add(parent + "_" + item.Key);}}}return result;}} }總結(jié)
以上是生活随笔為你收集整理的JSON——Json对象扁平化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 计算机组成原理——加减运算 溢出判断
- 下一篇: wxpython 按钮 扁平化_jque