3

我正在用 C# 开发一个可以控制 SqueezeboxServer(SBS) 的应用程序。与 SBS 的通信是通过 JSON 消息发送到http://serverIP:9000/jsonrpc.js 所以我通过 HTTPWepRequest 发送 JSON 消息并通过 HTTPWebResponse 获得答案。

我得到的答案是 JSON 表示法的字符串。这就是问题开始的地方......现在我使用 JavaScriptSerializer 将 JSON 消息转换为对象。这是这样的:

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

这段代码给了我一个包含我要求的数据的对象。我要求的数据可能非常不同。有时答案是单个答案,而在其他情况下可能是多个答案。

让我们考虑一下我包含的两个图像:

第一个显示了反序列化器返回后的对象。您可以看到该对象是具有 4 个键值对的字典。我感兴趣的kvp是第4个。关键的“结果”是保存我需要的数据的那个。但是这个键有另一个字典作为值。这一直持续到我想要的实际数据,即专辑名称及其 ID。

替代文字

在第二张图片中,我想要的数据是属于“_count”键的值 0。如您所见,这个对象不那么复杂。

替代文字

所以我的问题的底线是我如何制定一个可以检索我想要的信息但适用于不同类型的对象(如不同深度)的解决方案?

希望任何人都可以向我发送正确的方向。

谢谢!

4

1 回答 1

0

您可以使用 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;
  }

 }
}

然后反序列化

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

JavaScriptSerializer.Deserialize - 如何更改字段名称

于 2011-09-28T22:43:43.607 回答