且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用NET Framework 3.5解析JSON。无法从对象获取数据

更新时间:2022-06-16 10:47:28

您正在反序列化到 Object ,该对象不会公开值属性。 json表示已序列化的对象,因此***将其反序列化为相同的类型:

You are deserializing to Object which wont expose the value properties. json represents a serializied object, so it is better to deserialize to the same Type:

public class UserMsg
{
    public string user { get; set; }
    public string msg { get; set; }
}

将其用作值目标类型:

string jstr = ...from whereever
JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, UserMsg> myCol = jss.Deserialize<Dictionary<string, UserMsg>>(jstr);

// test result:
foreach (KeyValuePair<string, UserMsg> kvp in myCol)
{
    Console.WriteLine("Key: {0}", kvp.Key);
    Console.WriteLine("  Value: {0}, {1}", kvp.Value.user, kvp.Value.msg);
}

输出:


键:365

值:admin,退出

键:366

值:用户,输入

(etc)

Key: 365
Value: admin, exit
Key: 366
Value: user, enter
(etc)

VS将有助于创建此类:将有效的json放在剪贴板上;然后

编辑菜单->选择性粘贴->将Json粘贴为类

VS will help make the class: put the valid json on the clipboard; then
Edit Menu -> Paste Special -> Paste Json as Class.

您可能需要调整一些内容。我认为是在VS2010中添加了此功能。

You may have to tweak a few things. I think it was VS2010 where this feature was added.