0

我正在尝试使用 JavaScriptSerializer 读取 JSON 对象。目前我无法用我的代码读取 JSON 对象。

下面是我的 JSON 对象。

{"data":[{"id":17,"name":"RedBug Project","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0}},{"id":14,"name":"RedRock","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0},"children":[{"id":16,"name":"WEB","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":14}}]}]}

读取 JSON 的方法

public Dictionary<string, string> ReadJSONProject(string jsObject)
        {

            var json = jsObject;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            dynamic jsonObject = serializer.Deserialize<dynamic>(json);

            Dictionary<string, string> dic = new Dictionary<string, string>();

            foreach (var item in jsonObject)
            {
                var a = item;
                dic.Add(item["id"], item["name"]);

            }

            return dic;
        }

我需要将以下值读入字典

"id":17,"name":"RedBug Project"

"id":14,"name":"RedRock"
4

4 回答 4

2
namespace WebApplication2
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string s = @"{""data"":[{""id"":17,""name"":""RedBug Project"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0}},{""id"":14,""name"":""RedRock"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0},""children"":[{""id"":16,""name"":""WEB"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":14}}]}]}";
            ReadJSONProject(s);
        }

        protected Dictionary<string, string> ReadJSONProject(string jsObject)
        {

            var json = jsObject;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            dynamic jsonObject = serializer.Deserialize<dynamic>(json);

            Dictionary<string, string> dic = new Dictionary<string, string>();

            var data = jsonObject["data"];

            foreach (var record in data)
            {
                var id = ((int)record["id"]).ToString();
                var name = record["name"] as string;

                dic.Add(id, name);

            }

            return dic;
        }
    }
}
于 2013-10-09T04:05:31.387 回答
0

请参考以下示例并根据您的需要进行修改。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Threading;
using System.Xml;
using ConsoleDemo.Controller;
using ConsoleDemo.Model;
using Microsoft.Practices.Unity;


namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = @"{""Root"": {""data"": [{""CardName"": ""card1"",""functions"": [{""State"": ""OPEN""},{""State"": ""INHERENT""}]},{""CardName"": ""card2"",""functions"": [{""State"": ""CLOSED""},{""State"": ""INHERENT""}]}]}";
            RootClass dynObj = JsonHelper.JsonDeserialize<RootClass>(data); //Get the object
            Console.ReadKey();
        }
    }

    [DataContract]
    public class RootClass
    {
        [DataMember(Name = "Root")]
        public Data Root { get; set; }
    }

    [DataContract]
    public class Data
    {
        [DataMember(Name = "data")]
        public List<Card> data { get; set; }
    }

    [DataContract]
    public class Card
    {
        [DataMember(Name = "CardName")]
        public string CardName { get; set; }

        [DataMember(Name = "functions")]
        public List<Function> Functions { get; set; }
    }

    [DataContract]
    public class Function
    {

        [DataMember(Name = "State")]
        public string State { get; set; }
    }

    public class JsonHelper
    {
        /// <summary>
        /// JSON Serialization
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            var ser = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream();
            ser.WriteObject(ms, t);
            var jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }
        /// <summary>
        /// JSON Deserialization
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            var ser = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            var obj = (T)ser.ReadObject(ms);
            return obj;
        }
    }

}
于 2013-10-09T03:52:34.607 回答
0

在 foreach 循环中检索成员“数据”,它是一个数组。您需要迭代此数组的元素以访问“id”和“name”。

于 2013-10-09T04:11:18.167 回答
0

这是我不使用动态的实现顺便说一句,您可以使用http://json2csharp.com/轻松地将复杂的 json 转换为 c# 类

public class Item
{
    public string id { get; set; }
    public string name { get; set; }
    public bool can_modify { get; set; }
    public string description { get; set; }
    public string start_date { get; set; }
    public string due_date { get; set; }
    public bool is_active { get; set; }
    public Item parent { get; set; }
    public List<Item> children { get; set; }
}

public class RootObject
{
    public List<Item> data { get; set; }
}

public Dictionary<string, string> ReadJSONProject(string jsObject)
{

    var json = jsObject;
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var jsonObject = serializer.Deserialize<RootObject>(json);
    Dictionary<string, string> dic = new Dictionary<string, string>();

    foreach (var item in jsonObject.data)
    {
        dic.Add(item.id, item.name);
    }

    return dic;
}
于 2013-10-09T04:15:59.030 回答