简体   繁体   English

如何从 JavaScriptSerializer 生成的对象中提取信息

[英]How to extract information from an Object produced by JavaScriptSerializer

I'm developing an application in C# which can control a SqueezeboxServer(SBS).我正在用 C# 开发一个可以控制 SqueezeboxServer(SBS) 的应用程序。 Communicating to the SBS is via JSON messages to http://serverIP:9000/jsonrpc.js So I send JSON messages via a HTTPWepRequest and get answers via an HTTPWebResponse.与 SBS 的通信是通过 JSON 消息发送到http://serverIP:9000/jsonrpc.js所以我通过 HTTPWepRequest 发送 JSON 消息并通过 HTTPWebResponse 获得答案。

The answer I get is a String in JSON notation.我得到的答案是一个 JSON 表示法的字符串。 And this is where the problems start... For now I convert the JSON message to a Object with the JavaScriptSerializer.这就是问题开始的地方……现在我使用 JavaScriptSerializer 将 JSON 消息转换为对象。 This goes like this:这是这样的:

public static Object FromJSON(this string reply)
{
    JavaScriptSerializer deSerializer = new JavaScriptSerializer();
    return deSerializer.DeserializeObject(reply);
}

This code gives me an object which holds the data I ask for.这段代码给了我一个保存我要求的数据的对象。 The data I ask for can be very different.我要求的数据可能非常不同。 Sometimes the answer is a single answer while in other situations it can be multiple things.有时答案是一个单一的答案,而在其他情况下则可能是多个问题。

Let's consider the two images I've included:让我们考虑一下我包含的两个图像:

The first one shows the object after it has been returned by the deSerializer.第一个显示对象被 deSerializer 返回后。 You can see the object is a Dictionary with 4 key-value pairs.您可以看到该对象是一个包含 4 个键值对的 Dictionary。 The kvp I'm interrested in, is the 4th one.我感兴趣的 kvp 是第 4 个。 The key "result" is the one which hold the data I need.关键的“结果”是保存我需要的数据的结果。 But this key has another Dictonary as a value.但是这个键有另一个字典作为值。 And this goes on and on until the actual data I want, which is the album name and its ID.这一直持续到我想要的实际数据,即专辑名称及其 ID。

替代文字

In the second image the data I want is the value 0 which belongs to the "_count" key.在第二张图片中,我想要的数据是属于“_count”键的值 0。 As you can see, this object is less complicated.如您所见,此对象不那么复杂。

替代文字

So the bottomline of my question is how do I make a solution which can retrieve the information I want but works with differt kind of objects (as in different depths)?所以我的问题的底线是我如何制定一个解决方案,该解决方案可以检索我想要的信息但适用于不同类型的对象(如不同深度)?

Hope anybody can send me in the right direction.希望任何人都可以向我发送正确的方向。

Thanks!谢谢!

You can use a JavaScriptConverter to get better control of the deserialization experience.您可以使用 JavaScriptConverter 来更好地控制反序列化体验。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;
using System.Collections;

namespace System.Web.Script.Serialization.CS {
 public class ListItemCollectionConverter: JavaScriptConverter {

  public override IEnumerable <Type> SupportedTypes {
   //Define the ListItemCollection as a supported type.
   get {
    return new ReadOnlyCollection <Type> (new List <Type> (new Type[] {
     typeof(ListItemCollection)
    }));
   }
  }

  public override IDictionary <string, object> Serialize(object obj, JavaScriptSerializer serializer) {
   ListItemCollection listType = obj as ListItemCollection;

   if (listType != null) {
    // Create the representation.
    Dictionary <string, object> result = new Dictionary <string, object> ();
    ArrayList itemsList = new ArrayList();
    foreach(ListItem item in listType) {
     //Add each entry to the dictionary.
     Dictionary <string, object> listDict = new Dictionary <string, object> ();
     listDict.Add("Value", item.Value);
     listDict.Add("Text", item.Text);
     itemsList.Add(listDict);
    }
    result["List"] = itemsList;

    return result;
   }
   return new Dictionary <string, object> ();
  }

  public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer) {
   if (dictionary == null)
    throw new ArgumentNullException("dictionary");

   if (type == typeof(ListItemCollection)) {
    // Create the instance to deserialize into.
    ListItemCollection list = new ListItemCollection();

    // Deserialize the ListItemCollection's items.
    ArrayList itemsList = (ArrayList) dictionary["List"];
    for (int i = 0; i < itemsList.Count; i++)
     list.Add(serializer.ConvertToType <ListItem> (itemsList[i]));

    return list;
   }
   return null;
  }

 }
}

Then deserialize it然后反序列化

var serializer = new JavaScriptSerializer(); 
serialzer.RegisterConverters( new[]{ new DataObjectJavaScriptConverter() } ); 
var dataObj = serializer.Deserialize<DataObject>( json ); 

JavaScriptSerializer.Deserialize - how to change field names JavaScriptSerializer.Deserialize - 如何更改字段名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从jQuery / Javascript中的列表反序列化JavaScriptSerializer制作的Json对象 - How to a Deserialize Json object made by JavaScriptSerializer from a List in jQuery/Javascript 使用 JavaScriptSerializer() 从 C# 嵌套字典 object 中提取 JSON 数据 - Extract JSON data from C# nested dictionary object using JavaScriptSerializer() 如何从数据库中提取信息? - How to extract information from database? ASP.NET/C#:如何从Exception对象提取信息? - ASP.NET/C#: How to extract information from Exception object? JavaScriptSerializer反序列化为嵌套对象 - JavaScriptSerializer deserializing to a nested object 如何使用jQuery从JSON中提取信息 - how to extract information from JSON using jQuery JavaScriptSerializer 无法使用继承自 List 的属性序列化 object<t></t> - JavaScriptSerializer fails to serialise an object with a property inheriting from List<T> 如何让JavaScriptSerializer将子对象视为普通的旧字符串? - How to get JavaScriptSerializer to treat a sub-object as a plain old string? JavaScriptSerializer不会反序列化System.Drawing.Color。 如何反序列化Color对象? - JavaScriptSerializer is not deserializing System.Drawing.Color. How to deserialize Color object? 从路径中提取信息 - extract information from a path
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM