使用NET Framework 3.5解析JSON。无法从对象获取数据 [英] Parse JSON with NET Framework 3.5. Can't get data from object
问题描述
我只是无法获取json中嵌入对象的键和值。
我想获取这些键和值,例如 {user:‘admin’,msg:‘exit’}
。
通过此代码,我获得了item.Key(即json中的ID)和item.Value(System.Collections.Generic.Dictionary`2 [System.String,System.Object])
但是我只是不知道该对象做什么。如何从中获取数据?
我从服务器获取json-
I just can't get key and value for embedded object in json.
I want to get these keys and values like { user: 'admin', msg: 'exit' }
.
With this code I get item.Key (that is id in that json) and item.Value (System.Collections.Generic.Dictionary`2[System.String,System.Object])
But I just don't know what to do with this object. How to get data from it?
I get json from server -
{
"365": {
"user": "admin",
"msg": "exit"
},
"366": {
"user": "user",
"msg": "enter"
},
"370": {
"user": "user",
"msg": "exit"
},
"372": {
"user": "user",
"msg": "exit"
},
"373": {
"user": "admin",
"msg": "exit"
}
}
谢谢您的回答。
PS
我不想使用任何外部库。
P.S. I don't want to use any external libs.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Web.Script.Serialization;
namespace JSONTestconsole
{
class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
wc.Proxy = null;
string data = wc.DownloadString("http://temp.net");
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.DeserializeObject(data) as ICollection;
foreach (KeyValuePair<string, object> item in obj)
{
var id = item.Key;
Console.WriteLine(id);
Console.WriteLine(item.Value);
}
Console.ReadLine();
}
}
}
推荐答案
您正在反序列化到 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.
这篇关于使用NET Framework 3.5解析JSON。无法从对象获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!