首页 新闻 会员 周边 捐助

如何使用newtonsoft.json获取这种数据结构?

0
悬赏园豆:5 [已解决问题] 解决于 2016-09-08 20:40

其实就是调用企业号的接口时,读取一个部门下的所有员工信息。

其中userlist、extattr内的数据是批量的,我采用建实体类的方式,貌似行不动啊,求大神指点思路、再贴个代码,谢谢了〜〜

豆豆不多了。。。

问题补充:

感谢大家,还是园子里的好人多,真热心〜〜〜

自己提了问题后,又去debug了一次,发现报错是在department字段,才发现自己department写成string了,而微信官方返回的是int[],改了后就通了。

再次感谢大家的热心。

sfrost的主页 sfrost | 初学一级 | 园豆:9
提问于:2016-09-08 10:04
< >
分享
最佳答案
0

为什么不行?复制这个json字符串,

VS->打开一个cs文件->编辑->选择性粘贴->将json粘贴为类

获取到这个json的实体类.然后反序列化.

收获园豆:5
吴瑞祥 | 高人七级 |园豆:29449 | 2016-09-08 11:06

高手,小弟刚知道原来可以这样粘贴生成类,太方便了。

sfrost | 园豆:9 (初学一级) | 2016-09-08 20:38
其他回答(4)
0

userlist是数组啊,你建的类是怎么建的?

顾晓北 | 园豆:10893 (专家六级) | 2016-09-08 10:10
0

你把你的model贴出来看看

Eric.luo | 园豆:853 (小虾三级) | 2016-09-08 10:13
0

如果用的EF  在 主类 建立一个 icollection  或者list  类型的 属性 当然 例如  User{public int id{get;set;} List<Role> RoleList{get;set;}}  查询的时候记得 include RoleList 通过 JsonConvert  就能得到你要的结构

Постой! | 园豆:1084 (小虾三级) | 2016-09-08 10:36

你的 extattr 有点奇怪 难道不应该是 extattr:[{},{}]这样的结构? 感觉多套了一层?

支持(0) 反对(0) Постой! | 园豆:1084 (小虾三级) | 2016-09-08 10:42

@Постой!: 可能是微信考虑后期扩展的属性不止attr这一种结构,所以才这样多嵌套了一层。我也是后面才反应过来的,又多加了一层类实体。

支持(0) 反对(0) sfrost | 园豆:9 (初学一级) | 2016-09-08 20:35
0

推荐一个园友的帮助类,

var josnData =DynamicJson.Parse(str);

josnData.IsArray 返回是否是数组

var errmsg="";

if(josnData.IsDefined("errmsg")){ errmsg=josnData.errmsg; }

if(josnData.IsDefined("userlist"))

{

 var  userlist=josnData.userlist;

  if(userlist.IsArray)

  {

      foreach(var usr in userlist){

               //TODO 继续解析

          }

  }

}

以下为帮助类源代码

  1 /*--------------------------------------------------------------------------
  2 * DynamicJson
  3 * ver 1.2.0.0 (May. 21th, 2010)
  4 *
  5 * created and maintained by neuecc <ils@neue.cc>
  6 * licensed under Microsoft Public License(Ms-PL)
  7 * http://neue.cc/
  8 * http://dynamicjson.codeplex.com/
  9  * 博客园网友 夜の魔王 友情借用此代码,用于微信开发。
 10  * http://www.cnblogs.com/deepleo/
 11 *--------------------------------------------------------------------------*/
 12 using System;
 13 using System.Collections;
 14 using System.Collections.Generic;
 15 using System.Diagnostics;
 16 using System.Dynamic;
 17 using System.IO;
 18 using System.Linq;
 19 using System.Reflection;
 20 using System.Runtime.Serialization.Json;
 21 using System.Text;
 22 using System.Xml;
 23 using System.Xml.Linq;
 24 
 25 namespace GuaiPin.Shop.Common
 26 {
 27     public class DynamicJson : DynamicObject
 28     {
 29         private enum JsonType
 30         {
 31             @string, number, boolean, @object, array, @null
 32         }
 33 
 34         // public static methods
 35 
 36         /// <summary>from JsonSring to DynamicJson</summary>
 37         public static dynamic Parse(string json)
 38         {
 39             return Parse(json, Encoding.Unicode);
 40         }
 41 
 42         /// <summary>from JsonSring to DynamicJson</summary>
 43         public static dynamic Parse(string json, Encoding encoding)
 44         {
 45             using (var reader = JsonReaderWriterFactory.CreateJsonReader(encoding.GetBytes(json), XmlDictionaryReaderQuotas.Max))
 46             {
 47                 return ToValue(XElement.Load(reader));
 48             }
 49         }
 50 
 51         /// <summary>from JsonSringStream to DynamicJson</summary>
 52         public static dynamic Parse(Stream stream)
 53         {
 54             using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max))
 55             {
 56                 return ToValue(XElement.Load(reader));
 57             }
 58         }
 59 
 60         /// <summary>from JsonSringStream to DynamicJson</summary>
 61         public static dynamic Parse(Stream stream, Encoding encoding)
 62         {
 63             using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, encoding, XmlDictionaryReaderQuotas.Max, _ => { }))
 64             {
 65                 return ToValue(XElement.Load(reader));
 66             }
 67         }
 68 
 69         /// <summary>create JsonSring from primitive or IEnumerable or Object({public property name:property value})</summary>
 70         public static string Serialize(object obj)
 71         {
 72             return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(GetJsonType(obj)), CreateJsonNode(obj)));
 73         }
 74 
 75         // private static methods
 76 
 77         private static dynamic ToValue(XElement element)
 78         {
 79             var type = (JsonType)Enum.Parse(typeof(JsonType), element.Attribute("type").Value);
 80             switch (type)
 81             {
 82                 case JsonType.boolean:
 83                     return (bool)element;
 84                 case JsonType.number:
 85                     return (double)element;
 86                 case JsonType.@string:
 87                     return (string)element;
 88                 case JsonType.@object:
 89                 case JsonType.array:
 90                     return new DynamicJson(element, type);
 91                 case JsonType.@null:
 92                 default:
 93                     return null;
 94             }
 95         }
 96 
 97         private static JsonType GetJsonType(object obj)
 98         {
 99             if (obj == null) return JsonType.@null;
100 
101             switch (Type.GetTypeCode(obj.GetType()))
102             {
103                 case TypeCode.Boolean:
104                     return JsonType.boolean;
105                 case TypeCode.String:
106                 case TypeCode.Char:
107                 case TypeCode.DateTime:
108                     return JsonType.@string;
109                 case TypeCode.Int16:
110                 case TypeCode.Int32:
111                 case TypeCode.Int64:
112                 case TypeCode.UInt16:
113                 case TypeCode.UInt32:
114                 case TypeCode.UInt64:
115                 case TypeCode.Single:
116                 case TypeCode.Double:
117                 case TypeCode.Decimal:
118                 case TypeCode.SByte:
119                 case TypeCode.Byte:
120                     return JsonType.number;
121                 case TypeCode.Object:
122                     return (obj is IEnumerable) ? JsonType.array : JsonType.@object;
123                 case TypeCode.DBNull:
124                 case TypeCode.Empty:
125                 default:
126                     return JsonType.@null;
127             }
128         }
129 
130         private static XAttribute CreateTypeAttr(JsonType type)
131         {
132             return new XAttribute("type", type.ToString());
133         }
134 
135         private static object CreateJsonNode(object obj)
136         {
137             var type = GetJsonType(obj);
138             switch (type)
139             {
140                 case JsonType.@string:
141                 case JsonType.number:
142                     return obj;
143                 case JsonType.boolean:
144                     return obj.ToString().ToLower();
145                 case JsonType.@object:
146                     return CreateXObject(obj);
147                 case JsonType.array:
148                     return CreateXArray(obj as IEnumerable);
149                 case JsonType.@null:
150                 default:
151                     return null;
152             }
153         }
154 
155         private static IEnumerable<XStreamingElement> CreateXArray<T>(T obj) where T : IEnumerable
156         {
157             return obj.Cast<object>()
158                 .Select(o => new XStreamingElement("item", CreateTypeAttr(GetJsonType(o)), CreateJsonNode(o)));
159         }
160 
161         private static IEnumerable<XStreamingElement> CreateXObject(object obj)
162         {
163             return obj.GetType()
164                 .GetProperties(BindingFlags.Public | BindingFlags.Instance)
165                 .Select(pi => new { Name = pi.Name, Value = pi.GetValue(obj, null) })
166                 .Select(a => new XStreamingElement(a.Name, CreateTypeAttr(GetJsonType(a.Value)), CreateJsonNode(a.Value)));
167         }
168 
169         private static string CreateJsonString(XStreamingElement element)
170         {
171             using (var ms = new MemoryStream())
172             using (var writer = JsonReaderWriterFactory.CreateJsonWriter(ms, Encoding.Unicode))
173             {
174                 element.WriteTo(writer);
175                 writer.Flush();
176                 return Encoding.Unicode.GetString(ms.ToArray());
177             }
178         }
179 
180         // dynamic structure represents JavaScript Object/Array
181 
182         readonly XElement xml;
183         readonly JsonType jsonType;
184 
185         /// <summary>create blank JSObject</summary>
186         public DynamicJson()
187         {
188             xml = new XElement("root", CreateTypeAttr(JsonType.@object));
189             jsonType = JsonType.@object;
190         }
191 
192         private DynamicJson(XElement element, JsonType type)
193         {
194             Debug.Assert(type == JsonType.array || type == JsonType.@object);
195 
196             xml = element;
197             jsonType = type;
198         }
199 
200         public bool IsObject { get { return jsonType == JsonType.@object; } }
201 
202         public bool IsArray { get { return jsonType == JsonType.array; } }
203 
204         /// <summary>has property or not</summary>
205         public bool IsDefined(string name)
206         {
207             return IsObject && (xml.Element(name) != null);
208         }
209 
210         /// <summary>has property or not</summary>
211         public bool IsDefined(int index)
212         {
213             return IsArray && (xml.Elements().ElementAtOrDefault(index) != null);
214         }
215 
216         /// <summary>delete property</summary>
217         public bool Delete(string name)
218         {
219             var elem = xml.Element(name);
220             if (elem != null)
221             {
222                 elem.Remove();
223                 return true;
224             }
225             else return false;
226         }
227 
228         /// <summary>delete property</summary>
229         public bool Delete(int index)
230         {
231             var elem = xml.Elements().ElementAtOrDefault(index);
232             if (elem != null)
233             {
234                 elem.Remove();
235                 return true;
236             }
237             else return false;
238         }
239 
240         /// <summary>mapping to Array or Class by Public PropertyName</summary>
241         public T Deserialize<T>()
242         {
243             return (T)Deserialize(typeof(T));
244         }
245 
246         private object Deserialize(Type type)
247         {
248             return (IsArray) ? DeserializeArray(type) : DeserializeObject(type);
249         }
250 
251         private dynamic DeserializeValue(XElement element, Type elementType)
252         {
253             var value = ToValue(element);
254             if (value is DynamicJson)
255             {
256                 value = ((DynamicJson)value).Deserialize(elementType);
257             }
258             return Convert.ChangeType(value, elementType);
259         }
260 
261         private object DeserializeObject(Type targetType)
262         {
263             var result = Activator.CreateInstance(targetType);
264             var dict = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
265                 .Where(p => p.CanWrite)
266                 .ToDictionary(pi => pi.Name, pi => pi);
267             foreach (var item in xml.Elements())
268             {
269                 PropertyInfo propertyInfo;
270                 if (!dict.TryGetValue(item.Name.LocalName, out propertyInfo)) continue;
271                 var value = DeserializeValue(item, propertyInfo.PropertyType);
272                 propertyInfo.SetValue(result, value, null);
273             }
274             return result;
275         }
276 
277         private object DeserializeArray(Type targetType)
278         {
279             if (targetType.IsArray) // Foo[]
280             {
281                 var elemType = targetType.GetElementType();
282                 dynamic array = Array.CreateInstance(elemType, xml.Elements().Count());
283                 var index = 0;
284                 foreach (var item in xml.Elements())
285                 {
286                     array[index++] = DeserializeValue(item, elemType);
287                 }
288                 return array;
289             }
290             else // List<Foo>
291             {
292                 var elemType = targetType.GetGenericArguments()[0];
293                 dynamic list = Activator.CreateInstance(targetType);
294                 foreach (var item in xml.Elements())
295                 {
296                     list.Add(DeserializeValue(item, elemType));
297                 }
298                 return list;
299             }
300         }
301 
302         // Delete
303         public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
304         {
305             result = (IsArray)
306                 ? Delete((int)args[0])
307                 : Delete((string)args[0]);
308             return true;
309         }
310 
311         // IsDefined, if has args then TryGetMember
312         public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
313         {
314             if (args.Length > 0)
315             {
316                 result = null;
317                 return false;
318             }
319 
320             result = IsDefined(binder.Name);
321             return true;
322         }
323 
324         // Deserialize or foreach(IEnumerable)
325         public override bool TryConvert(ConvertBinder binder, out object result)
326         {
327             if (binder.Type == typeof(IEnumerable) || binder.Type == typeof(object[]))
328             {
329                 var ie = (IsArray)
330                     ? xml.Elements().Select(x => ToValue(x))
331                     : xml.Elements().Select(x => (dynamic)new KeyValuePair<string, object>(x.Name.LocalName, ToValue(x)));
332                 result = (binder.Type == typeof(object[])) ? ie.ToArray() : ie;
333             }
334             else
335             {
336                 result = Deserialize(binder.Type);
337             }
338             return true;
339         }
340 
341         private bool TryGet(XElement element, out object result)
342         {
343             if (element == null)
344             {
345                 result = null;
346                 return false;
347             }
348 
349             result = ToValue(element);
350             return true;
351         }
352 
353         public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
354         {
355             return (IsArray)
356                 ? TryGet(xml.Elements().ElementAtOrDefault((int)indexes[0]), out result)
357                 : TryGet(xml.Element((string)indexes[0]), out result);
358         }
359 
360         public override bool TryGetMember(GetMemberBinder binder, out object result)
361         {
362             return (IsArray)
363                 ? TryGet(xml.Elements().ElementAtOrDefault(int.Parse(binder.Name)), out result)
364                 : TryGet(xml.Element(binder.Name), out result);
365         }
366 
367         private bool TrySet(string name, object value)
368         {
369             var type = GetJsonType(value);
370             var element = xml.Element(name);
371             if (element == null)
372             {
373                 xml.Add(new XElement(name, CreateTypeAttr(type), CreateJsonNode(value)));
374             }
375             else
376             {
377                 element.Attribute("type").Value = type.ToString();
378                 element.ReplaceNodes(CreateJsonNode(value));
379             }
380 
381             return true;
382         }
383 
384         private bool TrySet(int index, object value)
385         {
386             var type = GetJsonType(value);
387             var e = xml.Elements().ElementAtOrDefault(index);
388             if (e == null)
389             {
390                 xml.Add(new XElement("item", CreateTypeAttr(type), CreateJsonNode(value)));
391             }
392             else
393             {
394                 e.Attribute("type").Value = type.ToString();
395                 e.ReplaceNodes(CreateJsonNode(value));
396             }
397 
398             return true;
399         }
400 
401         public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
402         {
403             return (IsArray)
404                 ? TrySet((int)indexes[0], value)
405                 : TrySet((string)indexes[0], value);
406         }
407 
408         public override bool TrySetMember(SetMemberBinder binder, object value)
409         {
410             return (IsArray)
411                 ? TrySet(int.Parse(binder.Name), value)
412                 : TrySet(binder.Name, value);
413         }
414 
415         public override IEnumerable<string> GetDynamicMemberNames()
416         {
417             return (IsArray)
418                 ? xml.Elements().Select((x, i) => i.ToString())
419                 : xml.Elements().Select(x => x.Name.LocalName);
420         }
421 
422         /// <summary>Serialize to JsonString</summary>
423         public override string ToString()
424         {
425             // <foo type="null"></foo> is can't serialize. replace to <foo type="null" />
426             foreach (var elem in xml.Descendants().Where(x => x.Attribute("type").Value == "null"))
427             {
428                 elem.RemoveNodes();
429             }
430             return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(jsonType), xml.Elements()));
431         }
432     }
433 }

 

alci | 园豆:233 (菜鸟二级) | 2016-09-08 10:52

感谢,不过代码太多了,陌生标签太多,新手才学习,所以先收着,后面再看。

支持(0) 反对(0) sfrost | 园豆:9 (初学一级) | 2016-09-08 20:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册