读取JSON对象

时间:2013-10-09 03:39:13

标签: c# javascript asp.net asp.net-mvc json

我正在尝试使用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 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分: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;
        }
    }

}

答案 2 :(得分:0)

在foreach循环中检索作为数组的成员“data”。您需要迭代此数组的元素以访问“id”和“name。”

答案 3 :(得分:0)

这是我的实现,不使用动态BTW,您可以使用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;
}