在.Net中解析自定义JSON对象?

时间:2010-09-14 13:44:01

标签: .net asp.net json

对于我的ASP.Net应用程序,我需要使用返回JSON对象的HTTP REST API。 以下是JSON的外观:

message: [
    {
    type: "message"
    href: "/messages/id/23"
    view_href: /this-is-a-test-message/m-p/23
    id: {
        type: "int"
        $: 23
            }
    },
    { //...
    }
]

我可以使用DataContractJsonSerializer类并定义自定义类。但是,我不确定像“$”这样的键会如何转换为.Net。

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

使用JSON.NET

看起来像是你想做的事情
using System;
using Newtonsoft.Json.Linq;

class Test
{
    static void Main(string[] args)
    {
        JObject top = new JObject(
            new JProperty("type", "message"),
            new JProperty("href", "/messages/id/23"),
            new JProperty("view_href", "/this-is-a-test-message/m-p/23"),
            new JProperty("id", new JObject(new JProperty("type", "int"),
                                            new JProperty("$", 23))));

        Console.WriteLine(top);

        // Round trip        
        string json = top.ToString();
        JObject reparsed = JObject.Parse(json);
    }
}

答案 1 :(得分:2)

我认为使用标准DataContractJsonSerializer以“$”字段读取数据没有问题。更多的问题我看到你的数据在JSON格式中不是。如果您的意思是问题中的数据只是一个将被序列化的对象,那么序列化的JSON数据将如下所示

{
    "message": [
        {
            "type": "message",
            "href": "\/messages\/id\/23",
            "view_href": "\/this-is-a-test-message\/m-p\/23",
            "id": {
                "type": "int",
                "$": 23
            }
        }
    ]
}

var json = '{"message":[{"type":"message","href":"\/messages\/id\/23","view_href":"\/this-is-a-test-message\/m-p\/23","id":{"type":"int","$":23}}]}'

所有属性都将被双引号并且斜杠将被转义(请参阅http://www.json.org/)。您可以在JSON Validator上验证数据是否是正确的JSON数据。

要读取DataContractJsonSerializer的数据(反序列化)或写入(序列化),您可以毫无问题地进行。就像我之前提到的那样,你应该只使用Name属性的DataMember属性:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;

namespace DataContractJsonSerializer4 {
    [DataContract]
    public class MyId {
        [DataMember (Order = 0)]
        public string type;
        [DataMember (Order = 1, Name="$")]
        public int value;
    }
    [DataContract]
    public class Message {
        [DataMember (Order = 0)]
        public string type { get; set; }
        [DataMember (Order = 1)]
        public string href { get; set; }
        [DataMember (Order = 2)]
        public string view_href { get; set; }
        [DataMember (Order = 3)]
        public MyId id { get; set; }
    }
    [DataContract]
    public class MessageCollection {
        [DataMember]
        public List<Message> message { get; set; }
    }

    class Program {
        static void Main (string[] args) {
            MessageCollection mc = new MessageCollection () {
                message = new List<Message> () {
                    new Message() {
                        type = "message",
                        href = "/messages/id/23",
                        view_href = "/this-is-a-test-message/m-p/23",
                        id = new MyId() { type="int", value=23}
                    },
                    new Message() {
                        type = "message",
                        href = "/messages/id/24",
                        view_href = "/this-is-a-test-message/m-p/24",
                        id = new MyId() { type="int", value=24}
                    }
                }
            };
            string json =
                "{" +
                    "\"message\": [" +
                        "{" +
                            "\"type\": \"message\"," +
                            "\"href\": \"\\/messages\\/id\\/23\"," +
                            "\"view_href\": \"\\/this-is-a-test-message\\/m-p\\/23\"," +
                            "\"id\": {" +
                                "\"type\": \"int\"," +
                                "\"$\": 23" +
                            "}" +
                        "}," +
                        "{" +
                            "\"type\": \"message\"," +
                            "\"href\": \"\\/messages\\/id\\/24\"," +
                            "\"view_href\": \"\\/this-is-a-test-message\\/m-p\\/24\"," +
                            "\"id\": {" +
                                "\"type\": \"int\"," +
                                "\"$\": 24" +
                            "}" +
                        "}" +
                    "]" +
                "}";

            DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (MessageCollection));
            using (MemoryStream ms = new MemoryStream (Encoding.Unicode.GetBytes (json))) {
                MessageCollection obj = ser.ReadObject (ms) as MessageCollection;
                Console.WriteLine ("JSON data can be read. The value of the fist $ field is {0}", obj.message[0].id.value);
                using (MemoryStream ms2 = new MemoryStream ()) {
                    ser.WriteObject (ms2, obj);
                    string serializedJson = Encoding.UTF8.GetString (ms2.GetBuffer (), 0, (int)ms2.Length);
                    Console.WriteLine (serializedJson);
                }
            }
            using (MemoryStream memoryStream = new MemoryStream ()) {
                memoryStream.Position = 0;
                ser.WriteObject (memoryStream, mc);

                memoryStream.Flush ();
                memoryStream.Position = 0;
                StreamReader sr = new StreamReader (memoryStream);
                string str = sr.ReadToEnd ();
                Console.WriteLine ("The result of custom serialization:");
                Console.WriteLine (str);
            }
        }
    }
}

该程序产生以下输出

JSON data can be read. The value of the fist $ field is 23
{"message":[{"type":"message","href":"\/messages\/id\/23","view_href":"\/this-is-a-test-message\/m-p\/23","id":{"type":"int","$":23}},{"type":"message","href":"\/messages\/id\/24","view_href":"\/this-is-a-test-message\/m-p\/24","id":{"type":"int","$":24}}]}
The result of custom serialization:
{"message":[{"type":"message","href":"\/messages\/id\/23","view_href":"\/this-is-a-test-message\/m-p\/23","id":{"type":"int","$":23}},{"type":"message","href":"\/messages\/id\/24","view_href":"\/this-is-a-test-message\/m-p\/24","id":{"type":"int","$":24}}]}

答案 2 :(得分:1)

DataContractJsonSerializer有很多限制,我个人没有很好的使用经验。

我建议使用JSON .NET,或者如果你使用的是.NET 4.0,可能是IDynamicObjectMetaProvider

后者的例子在这里,但还有其他几个简单的实现: http://www.charlierobbins.com/articles/2010/02/11/parsing-json-into-dynamic-objects-using-mgrammar-and-c-4-0/