【问题标题】:Parse JSON with NET Framework 3.5. Can't get data from object使用 NET Framework 3.5 解析 JSON。无法从对象获取数据
【发布时间】:2015-09-05 13:06:51
【问题描述】:

我只是无法在 json 中获取嵌入对象的键和值。 我想获得这些键和值,例如{ user: 'admin', msg: 'exit' }。 使用此代码,我得到 item.Key(即 json 中的 id)和 item.Value (System.Collections.Generic.Dictionary`2[System.String,System.Object]) 但我只是不知道如何处理这个对象。如何从中获取数据? 我从服务器获取 json -

{
    "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"
    }
}

感谢您的任何回答。

附: 我不想使用任何外部库。

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();
        }
    }
}

【问题讨论】:

  • 那不是有效的 json
  • 已修复,但仍不知道如何处理 item.Value 对象

标签: c# json .net-3.5


【解决方案1】:

您正在反序列化为Object,它不会公开值属性。 json代表一个序列化的对象,所以最好反序列化为同一个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
值:管理员,退出
密钥:366
值:用户,输入
(等)

VS 将帮助创建类:将有效的 json 放在剪贴板上;然后
编辑菜单 -> 选择性粘贴 -> 将 Json 粘贴为类

您可能需要调整一些东西。我认为是 VS2010 添加了此功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多